Quick Tip: Sticky Navigation on Document Scroll using jQuery

Quick Tip: How to Activate a Sticky Navigation on Document Scroll using jQuery

Posted in Javascript/jQuery, Web Design/Development | One Comment

I came across a post from Karthik Vadlapatla on Forrst who was looking for a way to make a navigation bar stick to the top when the document is scrolled down past a certain amount, as seen on the Zendesk website.  The effect basically involves attaching a scroll event to the document or window that will change the css on the menu when the document scroll past the top offset position of the menu bar.

The general reason for using this effect to improve accessibility in that the user does not have to scroll all the way back to the top of the page to access the navigation bar. The code below illustrates how this is done:


$(function(){

   var menuOffset = $('#menu')[0].offsetTop; // replace #menu with the id or class of the target navigation

   $(document).bind('ready scroll',function(){
       var docScroll = $(document).scrollTop();

   if(docScroll >= menuOffset){
       $('#menu').addClass('fixed');
    } else {
       $('#menu').removeClass('fixed');
    }

   });

});

The code above will add a class to the target navigation, allowing you to set some custom css that is attached to the class:


#menu.fixed{
    background: #777;
    position:fixed;
    left:0;
    top:0;
    width:100%;
}

You can view the full demo on jsFiddle.



One Comment to “Quick Tip: How to Activate a Sticky Navigation on Document Scroll using jQuery”


Recommended

Take Your WordPress Skills to the Next Level - Digging Into WordPress by Chris Coyier and Jeff Starr
Learn how you can market your business on Twitter
Get the Book now! Use 25% discount code 'november25'
Hostgator - Cheap and Reliable Web Hosting - WordPress friendly

Incoming Tweets