How to Use jQuery to Create a Sticky Navigation on Scroll

Creating "sticky" elements is something that can often be done simply by using CSS to change an element's position from relative or absolute to fixed. The process of creating a sticky element is usually pretty straightforward. If you want to create a sticky or fixed element that is more dynamic, however, you'll have to use a little jQuery or JavaScript.

An example of a sticky element that's dynamic is one that is not always fixed or sticky, but only becomes that way under particular conditions or as a response to a certain trigger event. A more specific example of this phenomenon (and a common one that we've probably all seen) is the concept of a sticky navigation bar. A sticky header typically has relative positioning when a page first loads, but once the user scrolls past this nav bar, it sticks to the top of the screen and stays put at the top until the user scrolls back up and past the defined threshold.

A sticky navigation bar is useful and can make for a good user experience because your user will always have access to the navigation bar no matter how far down a page they've scrolled. To learn how to easily create a sticky navigation bar for your site, check out the code snippet below.

$(window).scroll(function() {
    if ($(window).scrollTop() & gt; 200) {
        $('.nav').css({
            'position': 'fixed',
            'top': 0
        });
    } else {
        $('.nav').css({
            'position': 'relative',
            'top': 'none'
        });
    }
});

So the snippet above does a few things. First, it selects the window as an element, and using an if/else statement combined with the .scrollTop() method, it states that if the user has scrolled past more than 200 px of the window, the .nav element will have a position of fixed and a top value of 0 (this is achieved by using the .css() property). If the user has not scrolled past more than 200px of the window, then the .nav element will have a position of relative.

A similar effect can be observed on the website for The Lyre Comics. When the page first loads, you have the header followed by the navigation bar, like this:

Screen Shot 2017-04-23 at 10.14.53 AM

But as the user scrolls past the header, the nav becomes fixed or "stuck"to the top of the page, which looks like this:

Screen Shot 2017-04-23 at 10.15.41 AM

Feel free to customize the code so that the element names and the point that the user scrolls past to trigger the sticky navigation reflect your particular project.