Skip to content

Instantly share code, notes, and snippets.

@jmmcduffie
Last active August 29, 2015 13:56
Show Gist options
  • Save jmmcduffie/9338935 to your computer and use it in GitHub Desktop.
Save jmmcduffie/9338935 to your computer and use it in GitHub Desktop.
Progressively Enhanced Single-Page Navigation
// Add an event listener to the document
$(document).on( "click", "a[data-behavior='scrollTo']", function(event) {
// Check for a fragment on the clicked link
// `this.hash` = the fragment identifier
if ( this.hash !== "" ) {
// Animate the viewport's scroll position
$("html, body").animate({ scrollTop: $( this.hash ).offset().top }, 500);
// Prevent the fragment identifier from being added to the URL
// This at the end in case the script fails before this point
event.preventDefault();
}
});
<nav role="navigation" class="Navbar">
<h2>Primary Navigation</h2>
<ol>
<li><a href="#features">Features</a></li>
<li><a href="#how-it-works">How It Works</a></li>
<li><a href="#pricing">Pricing</a></li>
<li><a href="/signup">Sign Up</a></li>
</ol>
</nav>
...
<section id="features">
...
</section>
<nav role="navigation" class="Navbar">
<h2>Primary Navigation</h2>
<ol>
<li><a href="#features" data-behavior="scrollTo">Features</a></li>
<li><a href="#how-it-works" data-behavior="scrollTo">How It Works</a></li>
<li><a href="#pricing" data-behavior="scrollTo">Pricing</a></li>
<li><a href="/signup">Sign Up</a></li>
</ol>
</nav>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment