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
}
}
});Written by André Lucas
Related protips
1 Response
Thanks, Andre! Good code.
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Navigation
Authors
Did you know?
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#