With this solution you do not need any plugin and there's no setup required besides placing the script before your closing </body>
tag.
$("a[href^='#']").on("click", function(e) {
e.preventDefault();
$("html, body").animate({
scrollTop: $($(this).attr("href")).offset().top
}, 1000);
return false;
});
if ($(window.location.hash).length > 1) {
$("html, body").animate({
scrollTop: $(window.location.hash).offset().top
}, 1000);
}
On load, if there is a hash in the address, we scroll to it.
And - whenever you click an a
link with an href
hash e.g. #top
, we scroll to it.
##Edit 2020
If you want a pure JavaScript solution: you could perhaps instead use something like:
var _scrollToElement = function (selector) {
try {
document.querySelector(selector).scrollIntoView({ behavior: 'smooth' });
} catch (e) {
console.warn(e);
}
}
var _scrollToHashesInHrefs = function () {
document.querySelectorAll("a[href^='#']").forEach(function (el) {
el.addEventListener('click', function (e) {
e_scrollToElement(el.preventDefaultgetAttribute('href'));
_scrollToElement(el.getAttribute('href'));return false;
})
})
if (window.location.hash) {
_scrollToElement(window.location.hash);
}
}
_scrollToHashesInHrefs();