Last Updated: September 09, 2019
·
410
· andrelug

Simple Sticky navigaton

Some frameworks, like Zurb's Foundation, use third-party plugins (like magellan) to make a sticky navigatio. Although those plugins do some other things, sometimes we just want a simple sticky nav. This code here works just fine.

var nav = $('#nav-sticky'),
    next_element = $('#next-element'),
    nav_sticky = nav.offset().top; //get the Y-position of section


$(window).on({
    scroll:function(){ // fires when user scrolls
        var current_position = window.pageYOffset; // get the current window Y-Position
        if( current_position > nav_sticky ) {
            nav.addClass('sticky'); // add class to make the nav sticky using css
            next_element.css('margin-top',45); // don't let the next element go up (this needs to be the size of the nav)
        } else {
            nav.removeClass('sticky'); // remove sticky css class
            next_element.css('margin-top',0); // back the next element to its place
        }
    }
});

1 Response
Add your response

Thanks, Andre! Good code.

over 1 year ago ·