How to keep scrolling from jumping over items in the list using jquery? I have no problems when hovering over the list items in the list using the mouse. But when using the Up/Down arrow keys to scroll the list, some items get jump over or it appears it get jumped over.
For example, if the selected item is Item 6, it could jump over the next sequence item (Item 5) when using the Up arrow key.
Item 1 Item 2 Item 3 Item 4 Item 5 Item 6
$(document).ready(function(){
$('li').hover(function(){
j = $(this).parents("ul").find("li").index($(this));
$('.hoverColor').removeClass('hoverColor');
$(this).addClass('hoverColor');
});
j = -1;
$(document).keyup(function(e) {
if(e.keyCode == 38) // The Up arrow key
{
if(--j>0) {
j = 0;
}
$("li").removeClass('hoverColor');
$("li:eq(" + j + ")","ul").addClass('hoverColor');
} else if (e.keyCode == 40) {
if(++j >$("li", "ul").length-1){
j = $("li", "ul").length-1;
}
$("li","ul").removeClass('hoverColor');
$("li:eq(" + j + ")","ul").addClass('hoverColor');
}
});
});
Here's the html code
Testing Focus
$(document).ready(function(){ $('li').hover(function(){ j = $(this).parents("ul").find("li").index($(this)); $('.hoverColor').removeClass('hoverColor'); $(this).addClass('hoverColor'); }); j = -1; $(document).keyup(function(e) { if(e.keyCode == 38) // The Up arrow key { if(--j$("li", "ul").length-1) { j = $("li", "ul").length-1; } $("li","ul").removeClass('hoverColor'); $("li:eq(" + j + ")","ul").addClass('hoverColor'); // var str = $("li:eq(" + j + ")","ul").text(); // $("li:eq(" + j + ")","ul").scrollTop(str2.top); // $("#textArea").insertAtCaret(str); } }) });.hoverColor { background-color:#408080; color:white; } li { list-style-type:none; list-style-position:inside; text-align: left; margin-left: 8px; padding: 0px } div { overflow: scroll; width: 200px; height: 300px; }