javascriptjqueryhtmlscrollanchor

How to scroll an HTML page to a given anchor


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.


Solution

  • function scrollTo(hash) {
        location.hash = "#" + hash;
    }
    

    No jQuery required at all!