Skip to content

Instantly share code, notes, and snippets.

@zenman
Last active December 19, 2015 15:39
Show Gist options
  • Save zenman/5978045 to your computer and use it in GitHub Desktop.
Save zenman/5978045 to your computer and use it in GitHub Desktop.
var scrollToAnchor = function() {
//cache some variables
var scrollElement = 'html, body',
$window = $(window);
//grab all the anchor links
$("a[href^='#']").click(function(e) {
//stop immediate scroll
e.preventDefault();
//cache some variables
var $this = $(this),
//get the hash text
target = this.hash,
$target = $(target),
//you can add or subtract from this value
//to adjust the exact position
scroll = $target.offset().top;
//stop any current animation and then animate
$(scrollElement).stop().animate({
//scroll to the top of the id
'scrollTop': scroll
}, 500, 'swing', function() {
//set the hash in the url bar
window.location.hash = target;
//reset the top again (jumps in FF/IE) if
//you offset the scroll variable
$window.scrollTop(scroll);
});
});
}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment