Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically scroll to an Anchor Tag

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.

like image 852
Anders Avatar asked Nov 05 '08 16:11

Anders


People also ask

How do I scroll to anchor tag?

The easiest way to to make the browser to scroll the page to a given anchor is to add *{scroll-behavior: smooth;} in your style. css file and in your HTML navigation use #NameOfTheSection .

How do I scroll to a specific div in HTML?

If you want to scroll the current document to a particular place, the value of HREF should be the name of the anchor to which to scroll, preceded by the # sign. If you want to open another document at an anchor, give the URL for the document, followed by #, followed by the name of the anchor.


1 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.

like image 68
MikeeMike Avatar answered Oct 02 '22 00:10

MikeeMike