Programmatically scroll to an Anchor Tag

Anders picture Anders · Nov 5, 2008 · Viewed 47.9k times · Source

Consider the following code:

<a href="#label2">GoTo Label2</a>
... [content here] ...
<a name="label0"></a>More content
<a name="label1"></a>More content
<a name="label2"></a>More content
<a name="label3"></a>More content
<a name="label4"></a>More content

Is there a way to emulate clicking on the "GoTo Label2" link to scroll to the appropriate region on the page through code?

EDIT: An acceptable alternative would be to scroll to an element with a unique-id, which already exists on my page. I would be adding the anchor tags if this is a viable solution.

Answer

MikeeMike picture MikeeMike · Nov 5, 2008

This JS has generally worked well for me if you also put an ID on the element:

document.getElementById('MyID').scrollIntoView(true);

This is good as it will also position scrollable divs etc so that the content is visible.