A guide on using key arrows in JavaScript to navigate and focus on elements

When working on my HTML project, I have a list of elements that I want to be able to select using the arrow keys.

I've included my code here for reference: [http://jsfiddle.net/T8S7c/]

What I'm trying to achieve is when the arrow keys are pressed, the focus should move to the selected element as if it had a hover effect. (For instance, pressing the down key should move the focus to Ambaji on the first key press)

I have the key event code figured out, but I'm struggling with how to shift the focus on keypress.

If anyone has any suggestions or solutions, I would greatly appreciate the help!

Answer №1

My approach to tackling this issue involves establishing a specific sequence of links and utilizing a variable to indicate which link should be the focus.

let order = ["link1", "link2", "link3", "link4"];
let currentFocus = -1;

function updateCurrent(inc) {
    currentFocus = (currentFocus + inc) % order.length;
    currentFocus = Math.max(currentFocus, 0);
}

document.onkeydown = function(evt) {
    evt = evt || window.event;

    switch (evt.keyCode) {
        case 38:
            updateCurrent(-1);
            document.getElementById(order[currentFocus]).focus();
            break;
        case 40:
            updateCurrent(1);
            document.getElementById(order[currentFocus]).focus();
            break;
    }
}; 

Answer №2

Check out the revised version of your code below. You can also view it on this Fiddle: http://jsfiddle.net/K4J3p/9/

const links = document.getElementsByTagName("a");
let currentIndex = 0;
links[currentIndex].focus();

document.onkeydown = function(evt) {
    evt = evt || window.event;

    switch (evt.keyCode) {
        case 38: // Up arrow
            if(currentIndex > 0){links[--currentIndex].focus();}
            break;
        case 40:// Down arrow
           if(currentIndex < links.length){links[++currentIndex].focus();}
            break;
    }
}; 

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

Altering the Size of Text in HTML

Currently I am working on my website and the title appears as follows <h1><font face="tempus sans itc" color="White"><div style="text-align:center">Welcome To My Website. View My Projects Here</h1></div> Is there a way to in ...

Is it necessary to convert SCSS into CSS in React?

I have a query about whether it is necessary to first compile our scss files into css and then import the css files into our react components, or if we can simply import the scss directly into the components? I've successfully imported scss directly ...

How to retrieve the value from a JSON object when the key is unknown in JavaScript

Here is the JSON file I'm working with: { "status": 200, "msg": "OK", "result": { "files": { "count": 1, "pUnJbKzql0f2": { "name": "How ...

How can the value attribute be obtained from the click class?

$(document).on('click','.edit', function(){ var appid = $(this).getAttribute('value'); I am trying to figure out how to save the value of the "value" attribute for an image with the edit class. Can anyone help me with thi ...

Troubleshooting steps for resolving Heroku's "State changed from up to crashed" error caused by Mongoose connection issue

I am encountering an issue while deploying my Node.js/MongoDB app to Heroku. It crashes with the following error: MongooseServerSelectionError: connection <monitor> to 104.155.184.217:27017 closed Below are excerpts from my log: 2022-07-10T23:36:17. ...

How to handle Component binding change events in AngularJS

I have developed a component in AngularJS that displays data. However, when the customer binding changes, I need to call a service in the component controller, but it is not updating. Below is the code snippet: In my Test1.html file: <tab-customer tit ...

Challenge with adjusting opacity of background when hovering over a box

I've encountered an issue with the background transparency in the following demo. For some reason, it's not working properly. .figure .caption-mask:hover { background: rgba(0, 0, 0, 0.0); } I'm attempting to remove the opacity f ...

Continue looping in Javascript until an empty array is identified

Currently, I am in search of a solution to create a loop in Javascript that continues until the array of objects is empty. The object I am working with looks like this: "chain": { "evolves_to": [{ "evolves_to": [{ ...

Should the updater method be placed in the state or passed directly to the context?

Is it better to have this context setup like so: <MatchContext.Provider value={this.state.match}> Or should I structure it as follows in my state? match: { match: null, updateMatch: this.updateMatch }, Which approach is more eff ...

Electron / Atom Shell unable to locate specified module

I am completely new to npm, node, and Electron. Here is the structure of my folder: -package.json -index.html -main.js -js/myStuff.js -node_modules In the file myStuff.js, I have a line that says var chokidar = require('chokidar'); but it keep ...

strange occurrences of bootstrap.min.css.map popping up

While working on my e-commerce website using Node, Express, Mongoose, and Bootstrap, I encountered an unexpected issue related to "bootstrap.min.css.map". The error 'Cast to ObjectId failed for value "bootstrap.min.css.map" at path "_id" for model " ...

What is the best way to add HTML formatted text into Outlook?

In my Emacs, I've generated this syntax-highlighted code snippet and now want to paste it into an Outlook email with rendered HTML (without the actual HTML code). <pre> <span style="color: #a020f0; background-color: gtk_selection_bg_color;"& ...

Implement a fullscreen hero image on a specific blogroll template page in Wordpress

My portfolio website uses custom page templates for each page. The blog page is not the landing page, but an interior page. I have been able to add a custom hero image to every page template except for the blog page. Currently, I am using the content.php p ...

Using Jquery to store input values from within <td> elements in an array

I'm trying to capture user input from a dynamically changing table with 2 columns. How can I retrieve the data from each column separately? The size of the table is adjusted by a slider that controls the number of rows. Below is the structure of my ta ...

Is there a way to reach a different function within the value of the react Context.Provider?

Right now, I am learning how to utilize the react context API. Within my react Provider class, I have some state data and functions stored in the value={}. But I am curious, how can I call a function inside this value from another function within the same ...

Configuring route for serving static files in an Express server

I'm completely new to working with express, but I am eager to learn and follow the best practices. My goal is to serve files like CSS or index.html from a folder called 'public'. I have seen examples using .use and .get methods as shown belo ...

Best Practices for Handling Form State in ReactJS with Redux

Currently in ReactJS + Redux, I am utilizing Material-UI's TextField for a form where users input their firstName, lastName, birthMonth, birthDay, and birthYear. The existing setup works but appears redundant, especially when handling the birth date f ...

JavaScript for creating dropdown menus using Twitter Bootstrap

I've been struggling to get the dropdown menus in my Twitter Bootstrap project to function properly. Below is the code I have for the navbar: <div class="container-fluid"> <div class="row-fluid"> <div class="span12"> < ...

What causes the button's frame color to change when I click on it?

I am facing an issue with a button I created. When I click the button, the frame color changes and I cannot figure out why. I have attached images showing the button before and after it is clicked. Before: https://i.sstatic.net/5jpB1.png After: https://i ...

Using Q to conduct polling asynchronously with promises

I am facing a situation similar to the one discussed in this blog post: Polling with promises. The author explains using promises for polling until a JobID is returned. I intend to implement this using Q. I want to chain promises together but my attempts ...