Blog Post Icon
Blog
05/14/2015

Use jQuery and CSS to make a sticky navigation menu

Hello!

Some may argue that sticky navigation menus (menus that are fixed at the top or bottom of the page as you scroll) are a fashionable web design style. Whether or not its a “fad”, having a navigation bar that is fixed as you scroll throughout the the site is advantageous. This is especially so when you have a page that has a lot of content to scroll through. Keeping the navigation front-and-center as the end-user browses throughout a site will ensure a smooth user experience.

Having elements “stick” as you scroll doesn’t have to be just within the context of navigation. You might want to have a sticky newsletter signup, sales chat window or even an e-commerce “cart” block or widget.

We thought we would share a simple example that can be injected into any CMS or flat file template. The example includes HTML to generate the menu content that will be fixed, CSS to style the menu and then jQuery to “stick” the menu once you start scrolling down. The jQuery will inject css styles after you start scrolling in order to set the position and other elements.

So first you want to define the menu in HTML :


Very simple so far. Next we want to style the menu navigation container. What we define here is not really necessary, other than to make it look nice as a header menu.

.main-navigation {
        text-align: left;
        float: right;
        clear: right;
        margin: 45px 0 0 0;
        margin: 2.8125rem 0 0 0;
        width: 100%;
}

So we’re telling where the container will float, text alignment, margin and overall container width. We could add other interesting things like background color, border, link colors and all that stuff but to keep things simple for the purposes of this guide we are keeping it minimal.

The next part is where the actual magic happens. We will be loading jQuery that will be adding styling and classes to the “main-navigation” class which will be triggered as you start scrolling down :

jQuery(function($) {

// Create a clone of the navigation class called clone.
$('.main-navigation').addClass('original').clone().insertAfter('.main-navigation').addClass('cloned').css('position','fixed').css('top','0').css('margin-top','35').css('z-index','500').removeClass('original').hide();

// Trigger the sticky function after you scroll down
scrollIntervalID = setInterval(stickyTheMenu, 10);


function stickyTheMenu() {

  var orgElementPos = $('.original').offset();
  orgElementTop = orgElementPos.top;

    // once you scroll past original, show the cloned class only
  if ($(window).scrollTop() >= (orgElementTop)) {

    // Cloned element should always have same left position
    orgElement = $('.original');
    coordsOrgElement = orgElement.offset();
    leftOrgElement = coordsOrgElement.left;
    widthOrgElement = orgElement.css('width');
    $('.cloned').css('left',leftOrgElement+'px').css('top',0).css('width',widthOrgElement).show();
    $('.original').css('visibility','hidden');
  } else {
    // not scrolled past the.main-navigation; only show the original.main-navigation.
    $('.cloned').hide();
    $('.original').css('visibility','visible');
  }
}
});

So whats happening in the above code? Lets break it down a bit so we can talk about it in chunks :

$('.main-navigation').addClass('original').clone().insertAfter('.main-navigation').addClass('cloned').css('position','fixed').css('top','0').css('margin-top','35').css('z-index','500').removeClass('original').hide();

The first thing that happens is were’ cloning the main navigation class and adding a second class with the “fixed” positiong among other simple stylings like margin-top and z-index. The margin would definitely need to be adjusted depending on how many items you have in your navigation menu, how high you want it to be and whatever else is going on in your theme.

The other thing to note is that we are creating the style elements for the “sticky” menu right off the bat, but “hiding” it with jQuery. When the scroll function triggers, we will hide the original menu navigation and show the sticky menu navigation.

The next item is one of the more interesting things :

scrollIntervalID = setInterval(stickyTheMenu, 10);

What were doing is having jQuery trigger a function called “stickyTheMenu” after the scroll-down interval of 10 is met. When we trigger “stickyTheMenu” , we are essentially hiding the main navigation class and showing the (previously hidden) sticky menu :

    $('.cloned').css('left',leftOrgElement+'px').css('top',0).css('width',widthOrgElement).show();
    $('.original').css('visibility','hidden');

You can see above that we are basically flipping between the previously hidden class and the previously shown class (non sticky versus sticky menu-navigation). This gives the illusion that the menu is staying the same as you scroll down, but simply “sticking” to the top part of the browser. The remaining parts of the “stickyTheMenu” function are simply adding other style elements such as top position and inherited width and whatnot.

For a CMS like wordpress, you would simply inspect the element where the navigation class is being defined and enqueue the jQuery code illustrated above in the functions.php :

function shift8web_custom_scripts() {
    wp_enqueue_script( 'customjs', get_template_directory_uri() . '/js/custom.js', array(), true );
}
add_action( 'wp_enqueue_scripts', 'shift8web_custom_scripts' );

Once the above script is enqueued in WordPress, as long as you are using the same navigation class that is identified in the header template, the jQuery should apply properly. You could add different styling elements such as shrinking the logo image in the header (if you have a logo in your header menu) once you scroll down or other interesting effects like that. You could go further and accompany an implementation like this with other jQuery effects like jQuery Parallax.

I hope this is helpful!

At Shift8, we cater to all sorts of businesses in and around Toronto from small, medium, large and enterprise projects. We are comfortable adapting to your existing processes and try our best to compliment communication and collaboration to the point where every step of the way is as efficient as possible.

Our projects are typically broken into 5 or 6 key “milestones” which focus heavily on the design collaboration in the early stages. We mock-up any interactive or unique page within your new website so that you get a clear picture of exactly how your design vision will be translated into a functional website.

Using tools like Basecamp and Redpen, we try to make the process simple yet fun and effective. We will revise your vision as many times as necessary until you are 100% happy, before moving to the functional, content integration and development phases of the project.

For the projects that are more development heavy, we make sure a considerable amount of effort is spent in the preliminary stages of project planning. We strongly believe that full transparency with a project development plan ensures that expectations are met on both sides between us and the client. We want to ensure that the project is broken into intelligent phases with accurate budgetary and timeline breakdowns.

Approved design mock-ups get translated into a browse-ready project site where we revise again and again until you are satisfied. Client satisfaction is our lifeblood and main motivation. We aren’t happy until you are.

Need Web Design?

Fill out the form to get a free consultation.

shift8 web toronto – 416-479-0685
203A-116 geary ave. toronto, on M6H 4H1, Canada
© 2023. All Rights Reserved by Star Dot Hosting Inc.

contact us
phone: 416-479-0685
toll free: 1-866-932-9083 (press 1)
email: sales@shift8web.com

Shift8 Logo