Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll a list item such that it becomes visible?

Tags:

jquery

scroll

I have a list with a bunch of elements. Usually a scrollbar is required to show them all. I add items to the list at runtime. Is there some way to scroll a particular list element such that it is ensured to be visible?:

<ul id='parent'>
  <li>blah</li>
  ...
  <li id='nthItem'>blah</li>
</ul>

$('#parent').scrollChildToVisible('nthItem');

something like that?

Thanks

like image 396
user246114 Avatar asked Sep 05 '10 03:09

user246114


1 Answers

To scroll to an element you can use .animate().

Here's an example of a function that scrolls to a jQuery selector (like an ID):

  // This is a function that scrolls to $(selector)
function goToByScroll(selector){
      // Scroll
    $('html,body').animate({
        scrollTop: $(selector).offset().top},
        'slow');
}

You can trigger this function whenever it is necessary. For example right after you've added the element in question:

  // Append item
$("#parent").append("<li id='nthItem'>blah</li>");

  // Scroll to item using function above. 
goToByScroll("#nthItem");

jsFiddle example

Finally, to select an id in jQuery use

$("#nthItem") // correct for an ID

not

$("nthItem") // incorrect
like image 157
Peter Ajtai Avatar answered Nov 02 '22 23:11

Peter Ajtai