Skip to content

Instantly share code, notes, and snippets.

@iamravenous
Last active April 24, 2024 03:18
Show Gist options
  • Save iamravenous/e713bef764d126dd9d7e to your computer and use it in GitHub Desktop.
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
@Warface
Copy link

Warface commented Jun 25, 2021

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

jQuery("a[href*='#']:not([href='#'])").click(function(e) {

	  var hash = this.hash;
	  var section = jQuery(hash);

	  	if(jQuery(hash).length > 0){
	  		e.preventDefault();
	  

			if (hash) { 
				jQuery('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