Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 given moment there are no more then 10 visible li (the rest need to be scrolled to). how can i change the scroll position (using jquery) of the ul to a specific li?

any thoughts?

like image 548
Ran Avatar asked Jan 03 '11 09:01

Ran


2 Answers

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.

like image 158
lonesomeday Avatar answered Oct 16 '22 22:10

lonesomeday


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)
like image 41
Suncat2000 Avatar answered Oct 16 '22 22:10

Suncat2000