Skip to content Skip to sidebar Skip to footer

Scrolling To Li Element - Jquery

i have a 'ul' that contains lots of 'li' (several hundred), the ul has a fixed hight of about 400px and the css property overflow:scroll, each li has the height of 40px so in every

Solution 1:

You need to do something like this:

$('#yourUL').scrollTop($('#yourUL li:nth-child(14)').position().top);

If you want to animate it, do

$('#yourUL').animate({
     scrollTop: $('#yourUL li:nth-child(14)').position().top
}, 'slow');

Obviously adjust 14 for different lis.

Solution 2:

I got close using @lonesomeday's answer, but I found that I had to calculate the relative position of the specific li from the first li because it changed depending on the current scroll position of the containing ul.

$('#yourUL').scrollTop($('#yourUL li:nth-child(14)').position().top - $('#yourUL li:first').position().top)

Solution 3:

You can do like this:

$('html, body').animate({
     scrollTop:$('#ulID li:eq(1)').offset().top
}, 1000);

You need to adjust value to eq for specific li or you can even customize the selector.

Solution 4:

If anyone needs a vanilla JS version, the following is working well for me, the value of 50 is just so that I'm showing the whole item when I'm near the top of the list. You can adjust that.

functionupdateListSelection(liID) {

    var list = document.getElementById("id Tag Of The <UL> element"),
        targetLi = document.getElementById(liID); // id tag of the <li> element

    list.scrollTop = (targetLi.offsetTop - 50);
};

Post a Comment for "Scrolling To Li Element - Jquery"