Skip to content

Instantly share code, notes, and snippets.

@VovanR
Last active Jan 22, 2017
Embed
What would you like to do?
jQuery anchor scroll
[name^="anchor-"] {
display: block;
}
<a href="#anchor-foo">
Scroll to Target
</a>
Anchor
...
<a name="anchor-foo"></a>
Target
$('a[href*="#anchor-"]').on('click', function (e) {
var $this = $(this);
var $target = $(this.hash);
$target = $target.length ? $target : $('[name=' + this.hash.split('#')[1] + ']');
if ($target.length) {
var offset = parseInt($this.data('offset'), 10) || parseInt($target.data('offset'), 10) || 0;
var duration = parseInt($this.data('duration'), 10) || 250;
$('html, body').animate({
scrollTop: $target.offset().top - offset
}, duration);
e.preventDefault();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment