44

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.

Anders
  • 12,088
  • 34
  • 98
  • 146

8 Answers8

76

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.

TylerH
  • 20,799
  • 66
  • 75
  • 101
MikeeMike
  • 1,474
  • 1
  • 12
  • 7
11

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.

CubanX
  • 5,176
  • 2
  • 29
  • 44
  • This worked great for me, could still use an anchor. Webbrower control embedded in a winforms app. – FastAl Nov 23 '10 at 21:33
3

Moving to a anchor from server side, example is c#.

ClientScript.RegisterStartupScript(this.GetType(), "hash", "location.hash = '#form';", true);
Gareth Williams
  • 372
  • 1
  • 5
  • 10
2

I suppose this will work:

window.location="<yourCurrentUri>#label2";
mkoeller
  • 4,469
  • 23
  • 30
1

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

document.getElementsByName('label2')[0].focus();
tvanfosson
  • 524,688
  • 99
  • 697
  • 795
  • You have mistake in your code - it is document.getElementsByName. Source - http://stackoverflow.com/questions/7816863/how-to-use-document-getelementbyname-and-getelementbytag – Imants Volkovs Jun 08 '16 at 15:30
1

The solution

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

works well in almost all browsers, whereas I've noticed that in some browsers or in some mobile (such as some Blackberry versions) "scrollIntoView" function is not recognized, so I would consider this solution (a bit uglier than the previous one):

window.location.href = window.location.protocol + "//" + window.location.host + 
                       window.location.pathname + window.location.search + 
                       "#MyAnchor";
sebarmeli
  • 17,949
  • 7
  • 35
  • 40
0

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

-1

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';
TylerH
  • 20,799
  • 66
  • 75
  • 101
Ken Pespisa
  • 21,989
  • 3
  • 55
  • 63