Let’s assume we have three sibling elements (list items in this example, but it can be anything), like this:

<li id="1">One</li>
<li id="2">Two</li>
<li id="3">Three</li>

We want to cycle through them by pressing up/down keys. We want the “active” item to be highlighted somehow (say red text instead of black. All we need is some JavaScript:
var active_id = '1';
Element = document.getElementById(active_id);
Element.style.color = 'red';

document.onkeyup = KeyCheck;

function KeyCheck(e) {
var old_id = active_id;
var Key = (window.event) ? event.keyCode : e.keyCode;
switch (Key) {
case 40:
case 38:
if (active_id < 1) active_id += 3; if (active_id > 3) active_id -= 3;
Old = document.getElementById(old_id);
Old.style.color = 'black';
New = document.getElementById(active_id);
New.style.color = 'red';

Done. This code listens to keypress events, “filters” the Up/Down arrow presses and reacts to them by coloring our list items.

Demo on jsfiddle.

A later update: to loop through clickable links, just change < li > tags to < a href= > and add New.focus() at the end of KeyCheck(e) function.

Leave a Reply