How to scroll to an element inside a div?

Amr Elgarhy picture Amr Elgarhy · Mar 11, 2009 · Viewed 381.8k times · Source

I have a scrolled div and I want to have an event when I click on it, it will force this div to scroll to view an element inside. I wrote its JavasSript like this:

document.getElementById(chr).scrollIntoView(true);

but this scrolls all the page while scrolling the div itself. How to fix that?

I want to say it like this: MyContainerDiv.getElementById(chr).scrollIntoView(true);

Answer

Brian Barrett picture Brian Barrett · Oct 20, 2009

You need to get the top offset of the element you'd like to scroll into view, relative to its parent (the scrolling div container):

var myElement = document.getElementById('element_within_div');
var topPos = myElement.offsetTop;

The variable topPos is now set to the distance between the top of the scrolling div and the element you wish to have visible (in pixels).

Now we tell the div to scroll to that position using scrollTop:

document.getElementById('scrolling_div').scrollTop = topPos;

If you're using the prototype JS framework, you'd do the same thing like this:

var posArray = $('element_within_div').positionedOffset();
$('scrolling_div').scrollTop = posArray[1];

Again, this will scroll the div so that the element you wish to see is exactly at the top (or if that's not possible, scrolled as far down as it can so it's visible).