views:

11891

answers:

8

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.

+2  A: 

I suppose this will work:

window.location="<yourCurrentUri>#label2";
mkoeller
A: 

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

In Javascript,

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

Ken Pespisa
Wouldn't this break if you execute it more than once?http://www.mysite.com/mypage.htm#label2#label2
EndangeredMassa
+4  A: 

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
+32  A: 

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.

Mike.

MikeeMike
thanks mike this is actually exactly what I was looking for!
Anders
A: 

You can use "window.location.hash" to access the hash (#) portion directly.

window.location.hash = "#myAnchor"

I'm not sure if you need the "#" prefix or not, in this scenario.

EndangeredMassa
A: 

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

document.getElementByName('label2').focus();
tvanfosson
A: 

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

A: 

same here, works fine with Firefox 3.6.3

ropox