Alon Alon - 3 months ago 39
HTML Question

Scrolling inner div on key down and up

I have build an autocomplete container which displays the first four results and the rest are hidden and can be seen when scrolling the inner div element which holds all the results.

I have implemented the on key up when pressing the up and down keys in order to let the users navigate easily through the results but the inner div with the results isn't scrolling.

How can you scroll an element which has

overflow-y:hidden
and not the window ?

jsFiddle example here

In the example , just press any key inside the input box and use your arrows to go down, you will see that the div isn't scrolling

Answer

You can update your script to find the relative position of the selected element and scroll to it:

$(".someInput").on("keyup", function(e) {
   $(".wrapper").show(); 
    if (e.which == 40) {
        $('.element:not(:last-child).element-hover').removeClass('element-hover').next().addClass('element-hover');
    } else if (e.which == 38) {
        $('.element:not(:first-child).element-hover').removeClass('element-hover').prev().addClass('element-hover');    
    }
    //scroll to element:
    $(".wrapper .inner_div").scrollTop(0);//set to top
    $(".wrapper .inner_div").scrollTop($('.element-hover:first').offset().top-$(".wrapper .inner_div").height());//then set equal to the position of the selected element minus the height of scrolling div
});

http://jsfiddle.net/kMzR9/3/