1.1K
How to smooth scroll to an id after clicking a link from another page?
Say that you have a link in a page,
Click Me
It’s easy, and can be done using a few lines, with jQuery.
When using $(‘a[href*=\\#]’), it only/automatically applies to all anchors () with a hash (#).
Sample 1:
$(document).ready(function() {
$('a[href*=\\#]').on('click', function(e){
e.preventDefault();
$('html, body').animate({
scrollTop : $(this.hash).offset().top
}, 500);
});
});
Sample 2:
If you want to smooth scroll to an element on a new page, following code will work like charm, include the following code on that page:
$(document).ready(function() {
if (window.location.hash) {
var hash = window.location.hash;
$('html, body').animate({
scrollTop : $(hash).offset().top
}, 500);
};
});
Sample 3:
$(document).on("ready", function () { var urlHash = window.location.href.split("#")[1]; $('html,body').animate({ scrollTop: $('.' + urlHash + ', #' + urlHash +',[name='+urlHash+']').first().offset().top -100 }, 1000); });