Last active
November 16, 2016 12:23
-
-
Save jpederson/9496381 to your computer and use it in GitHub Desktop.
jQuery Smooth Scrolling
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
$(function() { | |
// scroll handler | |
var scrollToAnchor = function( id ) { | |
// grab the element to scroll to based on the name | |
var elem = $("a[name='"+ id +"']"); | |
// if that didn't work, look for an element with our ID | |
if ( typeof( elem.offset() ) === "undefined" ) { | |
elem = $("#"+id); | |
} | |
// if the destination element exists | |
if ( typeof( elem.offset() ) !== "undefined" ) { | |
// do the scroll | |
$('html, body').animate({ | |
scrollTop: elem.offset().top | |
}, 1000 ); | |
} | |
}; | |
// bind to click event | |
$("a").click(function( event ) { | |
// only do this if it's an anchor link | |
if ( $(this).attr("href").match(/^#/) ) { | |
// prevent default propagation | |
event.preventDefault(); | |
// scroll to the location | |
var href = $(this).attr('href').replace('#', ''); | |
scrollToAnchor( href ); | |
// if we have pushState | |
if ( history.pushState ) { | |
history.pushState( null, null, '#'+href ); | |
} | |
// fallback to prevent jitter | |
return false; | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just fixed an issue that prevented external links that had hashtags from working correctly. It now ensures the "href" attribute of the link starts with '#' rather than just containing it.