Sep 26, 2010

jQuery One Page Navigation Plugin

When appropriate, I am a fan of the one-page sites. I really like the ones that add smooth scrolling and highlight the navigation depending upon which part of the page you have scrolled to. Here are a few examples: Brizk Design and Crush + Lovely. I finally have a freelance project where a one-page site makes sense, so I needed to write the JavaScript to make the navigation work how I wanted.

I wanted the page to scroll smoothly when the navigation was clicked, so I used the jQuery ScrollTo plugin. I also wanted the page to automatically highlight the correct navigation section depending upon which section was scrolled to, and that was where I added my custom code.

If you want to skip ahead, you can check out the demo and download the plugin from GitHub.

The Markup

I started with an unordered list for the navigation and a bunch of sections:

<ul id="nav">
  <li class="current"><a href="#section-1">Section 1</a></li>
  <li><a href="#section-2">Section 2</a></li>
  <li"><a href="#section-3">Section 3</a></li>
</ul>

<div id="section-1">
  <strong>Section 1</strong>
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
  incididunt ut labore et dolore magna aliqua.</p>
</div>
<div id="section-2">
  <strong>Section 2</strong>
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor 
  incididunt ut labore et dolore magna aliqua.</p>
</div>
<div id="section-3">
  <strong>Section 3</strong>
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor 
  incididunt ut labore et dolore magna aliqua.</p>
</div>

The JavaScript

Then, I added jQuery, the ScrollTo plugin, and my plugin to the page:

<script src="jquery.js"></script>
<script src="jquery.scrollTo.js"></script>
<script src="jquery.nav.min.js"></script>

Finally, I just need to call my plugin on the navigation:

$(document).ready(function() {
  $('#nav').onePageNav();
});

Options

There are a few options for this plugin:

And that’s it. Check out the demo and download the plugin from GitHub.

Categories