Skip to content

Instantly share code, notes, and snippets.

@nicoknoll
Created April 26, 2015 11:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicoknoll/25604b7785b83eee94be to your computer and use it in GitHub Desktop.
Save nicoknoll/25604b7785b83eee94be to your computer and use it in GitHub Desktop.
Smooth scroll if #hash is on page
$(document).ready(function(){
$('a[href*="#"]').on('click',function (e) {
if(!($(this.hash).length)) return true;
e.preventDefault();
var target = this.hash;
var $target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 900, 'swing', function () {
window.location.hash = target;
});
});
});
@nicoknoll
Copy link
Author

If you click on a link including a #hash this script checks if hash is on site and scrolls in this case. Otherwise it jumps to the url.

@jenb0t
Copy link

jenb0t commented Sep 10, 2015

THANK YOU! This is the only code that's worked for me to keep the #hash in the link after smooth scroll.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment