Programmatically scroll to an Anchor Tag

Viewed 49359

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.

8 Answers

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.

Using javascript:

window.location.href = '#label2';

If you need to do it from the server/code behind, you can just emit this Javascript and register it as a startup script for that page.

I suppose this will work:

window.location="<yourCurrentUri>#label2";

If the element is an anchor tag, you should be able to do:

document.getElementsByName('label2')[0].focus();

no "#" when you use window.location.hash

you can just open the new URL with the name appended, for instance http://www.example.com/mypage.htm#label2

In JavaScript,

location.href = location.href + '#label2';
Related