Last active
April 24, 2024 03:18
-
-
Save iamravenous/e713bef764d126dd9d7e to your computer and use it in GitHub Desktop.
Automatically detects the hash and scroll smoothly to anchor link with URL hashchange
This file contains hidden or 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 to anchor link | |
* Automatically detects the hash and scroll smoothly to anchor link with URL hashchange | |
* Author: Franco Moya - @iamravenous | |
*/ | |
// If you need more autonomy, | |
// You can replace hash detection with a data-attribute | |
// e.g. $("[data-scroll='smooth']") | |
$("a[href*='#']:not([href='#'])").click(function(e) { | |
e.preventDefault(); | |
var hash = this.hash; | |
var section = $(hash); | |
if (hash) { | |
$('html, body').animate({ | |
scrollTop: section.offset().top | |
}, 1000, 'swing', function(){ | |
history.replaceState({}, "", hash); | |
}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This only work if hash are on the same page. If you need to load another page with the anchor, it's not working. Here's a quick fix
`