How to scroll an HTML page to a given anchor How to scroll an HTML page to a given anchor javascript javascript

How to scroll an HTML page to a given anchor


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

No jQuery required at all!


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();


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;