Quick Code: jQuery Sticky Navigation When User Scrolls

Sticky navigation is being used more and more on sites and there’s a good reason why. It improves the UX by making the menu available no matter where the user is on the page. Learn how to create a simple, light-weight jQuery sticky navigation below. Best of all, it’s easy to implement on existing site’s without having to change any existing HTML code!

Sticky navigation is being used more and more on sites and there’s a good reason why. It improves the UX by making the menu available no matter where the user is on the page. Learn how to create a simple, light-weight jQuery sticky navigation below. Best of all, it’s easy to implement on existing site’s without having to change any existing HTML code!

jQuery Sticky Navigation Effect

Without further adieu, let’s jump into the code.

The JavaScript

jQuery(function(){
  var menuOffset = jQuery('#site-navigation')[0].offsetTop;
  jQuery(document).bind('ready scroll',function() {
    var docScroll = jQuery(document).scrollTop();
    if(docScroll >= menuOffset) {
      jQuery('#site-navigation').addClass('fixed').css('width',jQuery('#masthead').width());
    } else {
      jQuery('#site-navigation').removeClass('fixed').removeAttr("width");
    }
   });
});

Fairly basic jQuery code. It will add a class to the navigation when a user scrolls beyond it. Only thing you’ll need to change here is the navigation selector, #site-navigation. Also, you may want to remove .css('width',jQuery('#masthead').width()). That part of the code is more specific to this site.

The CSS

#site-navigation.fixed{
  position:fixed;
  z-index: 9999;
  top:0;
}

Simple stuff! If you’ve got any questions or need help customizing it to meet your needs feel free to shoot me a line below.

Author: Ben Marshall

Red Bull Addict, Self-Proclaimed Grill Master, Entrepreneur, Workaholic, Front End Engineer, SEO/SM Strategist, Web Developer, Blogger

2 thoughts on “Quick Code: jQuery Sticky Navigation When User Scrolls”

Leave a Reply

Your email address will not be published. Required fields are marked *