Last active
January 22, 2017 12:31
-
-
Save VovanR/e3ff42d530ee747976a5 to your computer and use it in GitHub Desktop.
jQuery anchor scroll
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
[name^="anchor-"] { | |
display: block; | |
} |
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
<a href="#anchor-foo"> | |
Scroll to Target | |
</a> | |
Anchor | |
... | |
<a name="anchor-foo"></a> | |
Target |
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
$('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