the Forum

Creating a Sticky Navigation with jQuery and CSS

Posted on April 10, 2014 by Michael Rosario
Total Posts: 33  |  Join date: 03-12-11

First let's examine a fixed nav. You can easily convert any navigation to a fixed nav simply by adding the following:
#yourNav { position: fixed; top: 0px; z-index: 9999; } 
The fixed position allows the element to be positioned based on the window - in our case, top at zero. The z-index should be set to a high number so that the navigation will be the top "layer." For a sticky nav, we need a way to turn on/off the fixed positioning - we do this using jquery. See example nav:
<div class="navcontainer">
nav id="yourNav">
We follow that with the following CSS:
.navcontainer #yourNav { position: relative; }
.navcontainer.Sticky #yourNav { position: fixed; top: 0px; z-index: 9999; } 
So, the nav is only sticky when the navcontainer has a "Sticky" class. Now, let's use jQuery:
/* Sticky Navigation */
var sticky = $(".navcontainer").position(); // Get the position on load
$(window).scroll( function(){
= $(".navcontainer").position();  // Get the position on scroll
if($(".navcontainer").hasClass("Sticky"))// Check if it has the class
else {
".navcontainer").scrollTop()< Remove class
We use the code above to remove/add the "Sticky" class to the "navcontainer" class.

Tags: There are no tags for this entry.

There are no answers yet.  Add yours below.

add your answers here
comments powered by Disqus