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/ .
The following style rule hides an element on a web page: display: none; When you set the value of display to none, the affected element will disappear. This means the element will no longer take up any space on the web page.
The :visible selector selects every element that is currently visible. Visible elements are elements that are not: Set to display:none. Form elements with type="hidden"
To both hide an element and remove it from the document layout, set the display property to none instead of using visibility .
visibility:hidden hides the element, but it still takes up space in the layout. display:none removes the element from the document. It does not take up any space.
At the end where you add the class to the nextElement
call .scrollIntoView( false )
on it as well.
if(nextElement !== null) {
$(nextElement).addClass("selected");
nextElement.scrollIntoView(false); // added this line
}
Updated fiddle: http://jsfiddle.net/gaby/6fjnnu55/
You can use, .offset()
to find the top offset of your select box and of the the selected element.
You can then use .scrollTop
to set it, try something like:
var yourSelectInput = $('.select');
var nextElementTop = $(nextElement).offset().top; // get offset of element
var selectTop = yourSelectInput.offset().top; // get offset of select input
// set the scrollTop to the scroll input offset
// plus the difference of the option top offset
yourSelectInput.scrollTop(yourSelectInput.scrollTop() + (nextElementTop - selectTop));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With