Created
December 27, 2023 21:25
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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