Sticky nav on scroll using jQuery and CSS
Need your navigation bar to switch to a sticky nav once the user scrolls beyond the header? Here’s how:
jQuery:
1 2 3 4 5 6 7 8 9 10 11 |
jQuery(window).scroll( function(){ var headerHeight = $('.header').outerHeight(); var scrollPos = $(window).scrollTop(); if ( scrollPos >= headerHeight ) { $('.navbar').addClass('nav-fixed'); } else { $('.navbar').removeClass('nav-fixed'); } } |
CSS:
1 2 3 4 |
.nav-fixed { position: fixed; top: 0; } |
What’s happening here?
First, we trigger the scroll event on the window:
1 |
jQuery(window).scroll( function(){ |
We grab the height of the header:
1 |
var headerHeight = $('.header').outerHeight(); |
And the current vertical position of the scroll bar:
1 |
var scrollPos = $(window).scrollTop(); |
Then we check when the user has scrolled beyond the header by comparing the vertical position of the scroll bar to the height of the header:
1 |
if ( scrollPos >= headerHeight ) { |
If the user is currently scrolled further than the height of the header then we add our CSS class, and if the user is not further than the header, then we remove the class:
1 2 3 4 5 |
$('.navbar').addClass('nav-fixed'); } else { $('.navbar').removeClass('nav-fixed'); } } |
The CSS class simply positioned the navbar at the top of the window in a fixed position.
To extend things further, you might want to add a margin tweak to avoid jerkiness when the navbar becomes fixed also want to limit the sticky nav to wider viewports:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// sticky nav on desktop jQuery(window).scroll( function(){ var headerHeight = $('.header').outerHeight(); var navHeight = $('.navbar').outerHeight(); var scrollPos = $(window).scrollTop(); var windowWidth = $(window).width(); if ( scrollPos >= headerHeight && windowWidth > 767 ) { $('.navbar').addClass('nav-fixed'); $('.main').css('margin-top', navHeight); } else { $('.navbar').removeClass('nav-fixed'); $('.main').css('margin-top', '0'); } }); |
View the working demo.