Tim Butterfield
Fixed Menu when Scrolling

The aim is to have the navigation fixed when the user is scrolling and return back to its original position when scrolling back to the top.

jQuery Library

This will require the jQuery library; you can download it in jQuery site or use other library from Google CDN, Miscrosoft CDN and jQuery CDN.

HTML

This is our HTML menu element, this is just a standard HTML UL tag to make our menus but if you already have one then use that instead.

Note: If youre going to use your old menus make sure to replace the class in JS code.

<div class="nav-container">
<div class="nav">
    <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">Link 1</a></li>
        <li><a href="#">Link 2</a></li>
    </ul>
    <div class="clear"></div> /*clear floating div*/
</div>
</div>

CSS

To make our menu list horizontally we need to add CSS code.

.nav-container { background: url('images/nav_bg.jpg') repeat-x 0 0;}
.f-nav { z-index: 9999; position: fixed; left: 0; top: 0; width: 100%;} /* this make our menu fixed top */

.nav { height: 42px;}
.nav ul { list-style: none; }
.nav ul li{float: left; margin-top: 6px; padding: 6px; border-right: 1px solid #ACACAC;}
.nav ul li:first-child{ padding-left: 0;}
.nav ul li a { }
.nav ul li a:hover{ text-decoration: underline;}

The z-index is set high so we dont have any other absolute element over the top of our navigation.

Javascript

This small jQuery code contains the main functions of our fixed scroll menu.

jQuery("document").ready(function($){
    
    var nav = $('.nav-container');   // This is the css location of your menu
    
    $(window).scroll(function () {
        if ($(this).scrollTop() > 136) {   // Change this value to the height before the navigation
            nav.addClass("f-nav");  // This is the css class that fixes the navigation to the top
        } else {
            nav.removeClass("f-nav");   // This removes the css class that fixes the navigation to the top
        }
    });
 
});

So, if the top is greater than 136px in height from the top of the page, the menu is fixed in the and the f-nav CSS class is added. When the top is less than 136px from the top of the page, the CSS class is removed and the menu returns to normal.