Skip to content Skip to sidebar Skip to footer

How Can I Make Selected Item In Listbox Scroll To The Top?

I creating a simple list off of array items. Scroll bars will appear if the list is big. However, my question is - when an item is selected, I would like to see that item to the to

Solution 1:

You can use this code:

$('#scrollable li').on('click', function(e){
    $('#scrollable').animate({scrollTop: $(e.target).position().top + $('#scrollable').scrollTop()});
});

See also this JSFiddle: http://jsfiddle.net/729nX/1/


Solution 2:

after much googling, i found you can either use scrollTo() using javascript with a code similar to this

function scrollToElem(elem) {    
    if(pageElement != null){               
        window.scrollTo(elem.offsetTop, 0);    
    }
}
var elem= document.getElementById('your_element');
scrollToElem(elem);

or use use location.hash which seems to me the simplest solution with something alone the lines of

location.hash = '#' + 'your_element';

Solution 3:

in case you have a scroll bar in an element instead of the whole window.

Element.scrollTop - MDN

Element.scrollTop - W3 school

function onSelect(list, selectedItem){
    list.scrollTop = selectedItem.offsetTop - list.offsetTop;
}

Post a Comment for "How Can I Make Selected Item In Listbox Scroll To The Top?"