Skip to content

Instantly share code, notes, and snippets.

@tijsverkoyen
Last active December 11, 2015 11:38
Show Gist options
  • Save tijsverkoyen/4594679 to your computer and use it in GitHub Desktop.
Save tijsverkoyen/4594679 to your computer and use it in GitHub Desktop.
This snippet will animate the anchor links on the current page. Inspired on a script written by @mathiashelin
$(document).on('click', 'a[href*="#"]', function(e) {
var $anchor = $(this),
hash = $anchor.attr('href'),
url = hash.substr(0, hash.indexOf('#'));
hash = hash.substr(hash.indexOf('#'));
// if it is just the hash, we should reset it to body, which will make it scroll to the top of the page.
if(hash == '#') hash = 'body';
// check if we have an url, and if it is on the current page and the element exists
if((url == '' || url.indexOf(document.location.pathname) >= 0) && $(hash).length > 0) {
$('html, body').stop().animate({
scrollTop: $(hash).offset().top
}, 1000);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment