In your code, removing the "selected" class from the element will mean that you can't use ".selected" to target the element in the next line.
What I would do is to have a list of all the elements and a pointer to the current one. Change the pointer each time a key is pressed, then remove the class from any element in the list before adding it to the current one.
/* These are global */var currentItem = 0;var items = $(".menu li");/* Inside the event handler */$(document).keydown(function(event) { if (event.keyCode === 40) { // Move to the next element currentItem++; // Use only one of these // Either stop at last item if(currentItem >= items.length) currentItem = items.length - 1; // Or return to first item if(currentItem >= items.length) currentItem = 0; //////// } else if (event.keyCode === 38){ // Move to the previouselement currentItem++; // Use only one of these // Either stop at first item if(currentItem < 0) currentItem = 0; // Or move to last item if(currentItem < 0) currentItem = items.length - 1; //////// } // Remove selected class from all elements items.removeClass("selected"); // Add selected class to current item items.eq(currentItem).addClass("selected");}
It's hard to copy this code because it's all been placed on one line. I wonder, do you still have a copy of the correctly formatted code?
making a menu controlled by arrow keys with marker
in JavaScript
Posted
Sorry to necro, but...
It's hard to copy this code because it's all been placed on one line. I wonder, do you still have a copy of the correctly formatted code?
Thanks.