I'm using jQuery 1.12. I have a styled UL with LI elements. I use the below code to select these elements using the up or down arrows on the keyboard when the DIV has focus ...
$(".select").bind('keydown', function(event) {
var currentElement = $(this).find(".select-options li.selected");
if (currentElement.length == 0) {
currentElement = $(this).find(".select-options li")[0];
$(currentElement).addClass("selected");
return;
} // if
var nextElement;
switch(event.keyCode){
// case up
case 38:
nextElement = $(this).find(".select-options li")[($(this).find(".select-options li").index(currentElement) - 1) % $(this).find(".select-options li").length];
break;
case 40:
nextElement = $(this).find(".select-options li")[($(this).find(".select-options li").index(currentElement) + 1) % $(this).find(".select-options li").length];
break;
}
$(this).find(".select-options li").removeClass("selected");
if(nextElement !== null) {
$(nextElement).addClass("selected");
}
});
The problem is, if you continually click the down key (for example), eventually you won't be able to see the selected item. How do I adjust things so that the selected item is always visible? The Fiddle illustrating the problem is here -- http://jsfiddle.net/sge8g5qu/1/ .
selectMenu
widget, which is available and fully tested. You can also look at their code to see how they did it. – Steep