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 1:
function scrollTo(hash) {
location.hash = "#" + hash;
}
No jQuery required at all!
Solution 2:
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:
element_to_scroll_to.scrollIntoView();
Solution 3:
You can use jQuery's .animate(), .offset() and scrollTop
. Like
$(document.body).animate({
'scrollTop': $('#anchorName2').offset().top
}, 2000);
Example link: http://jsbin.com/unasi3/edit
If you don't want to animate, use .scrollTop() like:
$(document.body).scrollTop($('#anchorName2').offset().top);
Or JavaScript's native location.hash
like:
location.hash = '#' + anchorid;