Consider the following code:
<a href="#label2" rel="nofollow noreferrer noopener">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.
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
This JS has generally worked well for me if you also put an ID on the element:
This is good as it will also position scrollable divs etc so that the content is visible.
window.location.href = '#label2';
Moving to a anchor from server side, example is c#.
ClientScript.RegisterStartupScript(this.GetType(), "hash", "location.hash = '#form';", true);
I suppose this will work:
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";
If the element is an anchor tag, you should be able to do:
no “#” when you use window.location.hash
you can just open the new URL with the name appended, for instance
location.href = location.href + '#label2';