Created
December 26, 2015 21:41
-
-
Save zplume/797b193d810d7717b265 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/* | |
============================================================================== | |
Animated scroll-to-section | |
------------------------------------------------------------------------------ | |
Fancy animated scroll override for native browser scroll-to hyperlinks | |
which reference named anchor tags within the current page. | |
Requires jQuery. | |
============================================================================== | |
Sections should be defined in page content like so: | |
<a name="SectionId"></a> | |
Sections should be linked to in left nav like so: | |
<a href="#SectionId">Title of section</a> | |
Script should be included at the bottom of the page or executed in a post-page load function. | |
*/ | |
// get all links that start with '#'; | |
// if clicked, override default behaviour (instant scroll) and do animated scroll instead. | |
// skip links with '#' href as these don't reference a page section | |
$("a[href^='#']").click(function(e) { | |
var name = $(this).attr("href").substr(1); // get the section id, trim the '#' | |
if(name.length > 0) { // skip this anchor tag if the href is just '#' | |
e.preventDefault(); // prevent instant scroll | |
var sectionOffset = $("a[name=" + name + "]").offset().top; // get vertical offset of section | |
$("body").animate({ scrollTop: sectionOffset }, 500); // animated scroll | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment