Scroll through the list item so that it becomes visible?

I have a list with a bunch of items. Usually a scroll bar is required to view them. I add items to the list at runtime. Is there a way to scroll a specific list item so that it is visible ?:

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

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

something like that?

thank

+5
source share
1 answer

To jump to an element, you can use .animate () .

Here is an example of a function that scrolls into a jQuery selector (e.g. ID):

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

You can run this function whenever necessary. For example, immediately after adding this element:

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

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

JsFiddle example

Finally, to select idin jQuery, use

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

not

$("nthItem") // incorrect
+5

All Articles