Jquery – How to scroll to an element within an overflowed Div

jquery

I have 20 list items inside of a div that can only show 5 at a time. What is a good way to scroll to item #10, and then item #20? I know the height of all the items.

The scrollTo plugin does this, but its source is not super easy to understand without really getting into it. I don't want to use this plugin.

Let's say I have a function that takes 2 elements $parentDiv, $innerListItem, neither $innerListItem.offset().top nor $innerListItem.positon().top gives me the correct scrollTop for $parentDiv.

Best Answer

The $innerListItem.position().top is actually relative to the .scrollTop() of its first positioned ancestor. So the way to calculate the correct $parentDiv.scrollTop() value is to begin by making sure that $parentDiv is positioned. If it doesn't already have an explicit position, use position: relative. The elements $innerListItem and all its ancestors up to $parentDiv need to have no explicit position. Now you can scroll to the $innerListItem with:

// Scroll to the top
$parentDiv.scrollTop($parentDiv.scrollTop() + $innerListItem.position().top);

// Scroll to the center
$parentDiv.scrollTop($parentDiv.scrollTop() + $innerListItem.position().top
    - $parentDiv.height()/2 + $innerListItem.height()/2);