How do I scroll an overflowed div to a certain hashtag (anchor)?

user323094 picture user323094 · Sep 22, 2011 · Viewed 11.3k times · Source

On my webpage I have an overflowed div (i.e. with the vertical scrollbar). Inside the div, I have anchors with ids. When I put one of these ids in the URL (mypage.html#id), I want the div, not the page, to scroll to that anchor.

How do I do that, preferably with plain JavaScript? If it's too complex, I'll go with jQuery, but I'm not using it in this project for anything else.

Answer

Ariel picture Ariel · Sep 22, 2011
$('.overflow').scrollTop($('#anchor').offset().top);

There is no reason at all you can't convert this to standard javascript.

Note that the scroll will be off if there is a margin on the anchor element.