Setting cursor position in input field when navigating with arrow keys: What are the ways to achieve accessibility?

I have implemented arrow key navigation in a table, allowing navigation with the up, down, left, and right arrow keys. How can I ensure that the cursor always stays on the right side of the input field during navigation?

Check out my Stackblitz example here: https://stackblitz.com/edit/stackoverflow-72056135-ube6hj?file=app%2Ftable-basic-example.ts

Here is a snippet of my code:

// HTML

 <input class="edit-input || focus-cell" type="text"[formControl]="rowControl.get(column.attribute)" appArrowKeyNav>

// TS

/**
   * Use arrowKeys
   * @param object any
   */
  move(object) {
    const inputToArray = this.inputs.toArray();
    let index = inputToArray.findIndex((x) => x.element === object.element);
    switch (object.action) {
      case 'UP':
        index -= this.columns.length;
        break;
      case 'DOWN':
        index += this.columns.length;
        break;
      case 'LEFT':
        index--;
        break;
      case 'RIGTH':
        index++;
        break;
    }

    if (index >= 0 && index < this.inputs.length) {
      inputToArray[index].element.nativeElement.focus();
    }
  }

Answer №1

After reviewing my code, I made improvements by utilizing the setSelectionRange() method. Here is the optimized version of my code:

/**
   * Implement arrow key functionality
   * @param object any
   */
  move(object) {
    const inputToArray = this.inputs.toArray();
    let index = inputToArray.findIndex((x) => x.element === object.element);
    switch (object.action) {
      case 'UP':
        index -= this.columns.length;
        break;
      case 'DOWN':
        index += this.columns.length;
        break;
      case 'LEFT':
        index--;
        break;
      case 'RIGTH':
        index++;
        break;
    }

    if (index >= 0 && index < this.inputs.length) {
      // Set focus on the input element
      inputToArray[index].element.nativeElement.focus();
      // Move cursor to the end of the text in the input
      setTimeout(() => {
        if (inputToArray[index].element.nativeElement.value?.length > 0) {
          const pos = inputToArray[index].element.nativeElement.value.length;
          inputToArray[index].element.nativeElement.setSelectionRange(pos, pos);
        }
      }, 1);
    }
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tracking accurate responses with button click

In my quiz, I want to keep track of the correct answers selected by the player. When a player clicks on the correct answer, the counter should increase by one. At the end of the quiz, the HTML should display a message like "You got" + correct + "answers co ...

I am unable to modify values using ngModel

I am struggling to update the value in my service.year.ts file but it seems impossible... <select name="selectedyear" [disabled]="disabledPeriod" [(ngModel)]="selectedyear" (ngModelChange)="onChangeYear()"> <option [ngValue]="selectedyear" ...

What is the easiest way to clear browser cache automatically?

Hello, I have implemented an ajax auto complete function in one of my forms. However, I am facing an issue where over time, the suggestions get stored and the browser's suggestion list appears instead of the ajax auto complete list, making it difficul ...

Failure to specify the variable type can lead to the creation of automatic global variables

Recently, I stumbled upon this http://www.w3schools.com/js/js_scope.asp page which introduced me to the concept of "Automatic Global variables". Here is an example of how it works: // You can use carName variable here function myFunction() { carName ...

Struggling with setting up Role-Based Access Control (RBAC) with cookie authentication in React

I've been working on incorporating Role Based Access Control into a React app using cookies, but I'm struggling to understand its use. The idea was to create a context that retrieves the data stored in the cookie through a specific API endpoint d ...

Exploring the possibilities of accessing Vue.prototype within an .addEventListener function

I've been attempting to access the global object Vue.prototype.$firebase, which is declared in main.js. import Vue from "vue"; import App from "./App.vue"; import router from "./router"; import VueTailwind from "vue- ...

Changing the position of a Bootstrap popover dynamically from top to bottom

Struggling with the bootstrap popover here. I can't seem to change the popover position from top to bottom when it reaches the top of the viewport. I attempted to use placement: 'auto bottom' but unfortunately, it didn't do the trick f ...

Facing issues when attempting to link two databases using Express

Encountering an issue while attempting to use two Oracle databases simultaneously. My startup function only executes the first connection try-catch block, but displays the console log connection message of the second try-catch block without actually estab ...

The Docker Angular container is experiencing difficulty connecting to the Express server container, despite the fact that they are both on the same network

In my current setup, I have an Angular application running on a Nginx server within a Docker container. The base image for this container is nginx:stable-alpine and its name is "admin-users-cont". This container is part of a Docker network named "tutorial- ...

Troubleshooting Images in a React Application Integrated with WordPress API

I am struggling to understand why this GET request is consistently returning a 404 error. I have thoroughly tested the URL using Postman and everything seems to be in working order for the title and excerpt, but the images are causing some issues. Does a ...

Child component in Angular 2 that verifies the parent component

My goal is to have a component behave differently depending on its parent component. For example, in the scenarios below, the child component would exhibit slightly different behavior. Scenario A <parent-a> <child></child> </parent-a ...

How to set up an Angular ErrorHandler?

Attempted to register an Angular ErrorHandler in this simplified StackBlitz environment, but it seems that it's not capturing the error thrown within the constructor of the HelloComponent. Any insights on this issue? Your opinions? ...

Need help restarting a timer I've built in Angular with just a click?

I am in the process of developing a compact application that will help me keep track of my activities within a specific time frame. Once I input an activity into a field and click "OK," it should be added to a list. My current challenge lies in resetting ...

Is it possible to utilize a function within an Angular [routerLink] to define the query parameter?

When receiving a response from the API without an ID, it presents data fields like url, name, gender, culture, etc. However, I need to create a route to access specific character information using /characters/:id. Since there is no direct ID provided in th ...

Embed a variable into an HTML element without affecting the inner HTML content

I am trying to inject a specific string into an HTML tag <td anyElement="{{myString}}" >some random text here </td> My desired interpretation is as follows: <td anyElement='Some string'>some random text here </td> Howe ...

How should we provide the search query and options when using fuse.js in an Angular application?

Having previously utilized fuse.js in a JavaScript project, I am now navigating the world of Angular. Despite installing the necessary module for fuse.js, I'm encountering difficulties implementing its search functionality within an Angular environmen ...

"Prisma vs. Supabase: A Comparison of Image Uploading

I am encountering an issue with adding image URLs to the Prisma database. I have successfully uploaded multiple images from an input file to Supabase storage, but when I try to add their URLs to the database, I receive an error regarding property compatibi ...

What is the approach taken by Angular when it comes to managing dependency injection for a variety

In my project, I've designed an abstract class that serves as a foundation service for my other two services. Below is the snippet of code for this abstract class: import { Injectable } from '@angular/core'; export interface Book { title ...

AJAX request lacks the 'access-control-allow-origin' header

I'm currently integrating a weather API into my app to display real-time weather information. Although I've used this API before, I am now attempting to fetch the data asynchronously using AJAX to avoid full page reloads. Below is the JavaScrip ...

If the input is marked as checked, apply a class to the corresponding HTML element

I need to manipulate the .form-group class by adding it if the nearest hotelObj element is checked, and removing it when hotelObj is unchecked. Instead of using addClass(), I prefer to utilize css(). $(".form-group").click(function() { if ($(this).ch ...