Skip to content

Instantly share code, notes, and snippets.

@VovanR
Last active January 22, 2017 12:31
Show Gist options
  • Save VovanR/e3ff42d530ee747976a5 to your computer and use it in GitHub Desktop.
Save VovanR/e3ff42d530ee747976a5 to your computer and use it in GitHub Desktop.
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