How to scroll HTML page to given anchor?

Juha Syrjälä picture Juha Syrjälä · Jul 2, 2010 · Viewed 476k times · Source

I’d like to make the browser to scroll the page to a given anchor, just by using JavaScript.

I have specified a name or id attribute in my HTML code:

 <a name="anchorName">..</a>

or

 <h1 id="anchorName2">..</h1>

I’d like to get the same effect as you’d get by navigating to http://server.com/path#anchorName. The page should be scrolled so that the anchor is near the top of the visible part of the page.

Answer

Dean Harding picture Dean Harding · Jul 2, 2010
function scrollTo(hash) {
    location.hash = "#" + hash;
}

No jQuery required at all!