Skip to content

Instantly share code, notes, and snippets.

@bridgetwes
Created December 27, 2023 21:25
Show Gist options
  • Save bridgetwes/7ee61e7253161804dde057ae1caeda1f to your computer and use it in GitHub Desktop.
Save bridgetwes/7ee61e7253161804dde057ae1caeda1f to your computer and use it in GitHub Desktop.
jQuery smooth scroll to element from URL hash - on load or from in page link
//Smooth scroll on page load if anchor is in URL
if (window.location.hash) {
var hash = window.location.hash;
$('html,body').animate({
scrollTop: $(hash).offset().top - 200
}, 1000);
}
//Smooth scroll to anchor when clicking on a link
$('a[href*="#"]:not([href="#"])').click(function (event) {
event.preventDefault();
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') &&
location.hostname == this.hostname) {
var target = $(this.hash);
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top - 200
}, 1000);
return false;
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment