How To: Create a a fixed (sticky) scrolling navigation bar

Let’s face it, sticky/floating menus are a trend right now and besides being very nice, they’re very practical. So, what do you mean by sticky/floating elements? Basically, when you scroll down a webpage, you define an element that can stick to the browser window…in our case, the site’s menu or navigation bar.

For this short tutorial, we’re gonna use a a bit of CSS and a small jQuery function. This tutorial works for custom coded sites (html/php) and WordPress.

Let’s take a simple website structure example:

<div id="main">
<nav>
   <ul>
     <li><a href="#">Home</a></li>
     <li><a href="#">About</a></li>
     <li><a href="#">Team</a></li>
     <li><a href="#">Contact</a></li>
  </ul>
</nav>
</div>

The <nav> section being the site’s menu/navbar in our case. Keep in mind that menus can be enclosed in any classes or id’s (ex. <div id=”navbar”>). if that’s the case, you have to replace “nav” in the below jQuery function with your class – ex (‘#navbar’)

The CSS

Find your main CSS file and add the following class there (you can rename it as you see fit):

.floaty {
position: fixed;
min-width:100% !important;
z-index:9999;
}

For those unfamiliar with the CSS functions,  z-index:9999 will always display the bar on top.

The jQuery

If you’re running a WordPress site, you already have the jQuery library added by default. We need to add the library to the site, preferably in the site’s header, before the </head> tag:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

Now, in the header php file (or any file that’s loaded sitewide), we have to add this jQuery function:

<script>
jQuery(document).ready(function ($){
      $(window).bind('scroll', function() {
      var navHeight = ( $(window).scrollTop() );
         if (navHeight > 200) {
            $('nav').addClass('floaty');
         }
        else {
           $('nav').removeClass('floaty');
        }
});
});
</script>

This function simply checks when scrolling if you scrolled more than 200px and adds the class “fixedy” to the navbar class “nav“. You can modify the height as you see fit, usually, you’d want users to scroll a bit until they get the sticky menu.

Demo: You can see it in action by scrolling down anywhere on the site.