How do I scroll to an element within an overflowed Div?

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);

Leave a Comment