Last active
August 29, 2015 14:14
-
-
Save teeli/a1101aea9592cb78586b to your computer and use it in GitHub Desktop.
Animate scroll to anchor on hash links (jQuery)
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
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