How to scroll HTML page to given anchor?

05/17/2020 09:00:01

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>


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

I’d like to get the same effect as you’d get by navigating to The page should be scrolled so that the anchor is near the top of the visible part of the page.

Verified Answer (348 Votes)

07/02/2010 11:25:24
function scrollTo(hash) {
    location.hash = "#" + hash;

No jQuery required at all!


Answer #2 (223 Votes)

07/03/2010 06:24:24

Way simpler:

var element_to_scroll_to = document.getElementById('anchorName2');
// Or:
var element_to_scroll_to = document.querySelectorAll('.my-element-class')[0];
// Or:
var element_to_scroll_to = $('.my-element-class')[0];
// Basically `element_to_scroll_to` just have to be a reference
// to any DOM element present on the page
// Then:

Answer #3 (123 Votes)

07/02/2010 11:22:21

You can use jQuerys .animate(), .offset() and scrollTop. Like

    'scrollTop':   $('#anchorName2').offset().top
}, 2000);

example link:

If you don't want to animate use .scrollTop() like


or javascripts native location.hash like

location.hash = '#' + anchorid;
Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.