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
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");
Finally, to select an id
in jQuery use
$("#nthItem") // correct for an ID
not
$("nthItem") // incorrect
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With