Skip to content

Instantly share code, notes, and snippets.

@teeli
Last active August 29, 2015 14:14
Show Gist options
  • Save teeli/a1101aea9592cb78586b to your computer and use it in GitHub Desktop.
Save teeli/a1101aea9592cb78586b to your computer and use it in GitHub Desktop.
Animate scroll to anchor on hash links (jQuery)
var offset = offset || 0;
$('a[href*=#]').on('click', function (event) {
event.preventDefault();
// create a dummy element on current scroll position so we can write hash to document.location without scrolling immediately
$('body').prepend('<div style="position: absolute;top:' + window.scrollY + 'px" id="' + this.hash.substr(1) + '" class="scroll-placeholder"></div>');
document.location.hash = this.hash.substr(1);
$(this.hash + '.scroll-placeholder').remove();
// animate scroll
$('html,body').animate({scrollTop: $(this.hash).offset().top + offset}, 500);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment