26 April 2016

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:



What’s happening here?

First, we trigger the scroll event on the window:

We grab the height of the header:

And the current vertical position of the scroll bar:

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:

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:

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:

View the working demo.