Project Avant Facebook Page Project Avant Twitter Page

tutorial #2: Sticky Navigation

Besides easing, jQuery can also enhance scrolling. You will see how to use jQuery to make a sticky navigation bar.

For this demonstration, you will see how to create a sticky navigation. You will learn how to build the jQuery code needed and learn the purpose of each line, as well as how to create the elements needed for the sticky navigation in HTML and CSS.

Below is a demonstration of a sticky navigation. Scroll down the page and see this demo’s navigation bar stick to the top.

The How-To

HTML

 
         			
     <div id="stickynav">
    
        <ul>
          
          <li id="#">
          		 <a href="#">Home </a>
          </li>
          
          <li>
          		 <a href="#">Buy </a>
          </li>
          
          <li>
          		 <a href="#">Sell </a>
         </li>
          
         <li>
          		 <a href="#">About Us </a>
          </li>
          
         <li>
          		 <a href="#">Contact </a>
          </li>
        
        </ul>
	
    </div>			
                              
     

CSS

#stickynav {
	position: relative;
	background:#155a7a;
	height:50px;
	text-align:center;
	margin:0 auto;
	z-index:10;
}

#stickynav ul li {
	display:inline-block;
	list-style:none;
	padding:10px;
}

#stickynav a {
	color:#FFFFFF;
}

#stickynav.fixed {
	position: fixed;
	top: 0;
    left: 25%;
    right: 25%;
} 

jQuery

$(document).ready(function() {
//Once the page is readyThe functions will be executed.
var $window = $(window),
$stickynav = $("#stickynav");//Select the element with the id of 'sticynav'.
$window.scroll(function() {//Calls for a scroll event.
if (!$stickynav.hasClass("fixed") && ($window.scrollTop() > $stickynav.offset().top)) {
//Will make sure the element will stay on top of the webpage.
$stickynav.addClass("fixed").data("top", $stickynav.offset().top);
//Will add a 'fixed' position to the element.
}
else if ($stickynav.hasClass("fixed") &&
($window.scrollTop() < $stickynav.data("top"))) { //Checks to see if the element has a class 'fixed'. $stickynav.removeClass("fixed"); //Will return the element's normal position when the conditions are met. } }); });//Close.