Skip to content

Instantly share code, notes, and snippets.

@zplume
Created December 26, 2015 21:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zplume/797b193d810d7717b265 to your computer and use it in GitHub Desktop.
Save zplume/797b193d810d7717b265 to your computer and use it in GitHub Desktop.
/*
==============================================================================
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