This is a simple requirement and I cannot make it work.
I simply want to navigate through a using arrow keys.Also I want to detect when a arrow key is pressed on a
How about something like this jsFiddle?
Basically it maintains a simple index of which list item is currently selected. The up and down arrow keys are bound to the keydown event and if someone presses the up arrow at the top of the list, the top item stays selected and vice-versa.
var chosen = "";
$(document).keydown(function(e){ // 38-up, 40-down
if (e.keyCode == 40) {
if(chosen === "") {
chosen = 0;
} else if((chosen+1) < $('li').length) {
chosen++;
}
$('li').removeClass('selected');
$('li:eq('+chosen+')').addClass('selected');
return false;
}
if (e.keyCode == 38) {
if(chosen === "") {
chosen = 0;
} else if(chosen > 0) {
chosen--;
}
$('li').removeClass('selected');
$('li:eq('+chosen+')').addClass('selected');
return false;
}
});