Sticky Nav using vanilla JavaScript

Screenshot of a sticky nav bar that uses vanilla Javascript.

I didn’t realise how easy it would be to make a sticky nav bar that uses vanilla Javascript.

This is something I’ve been wanting to learn for a long time. I was surprised how easy it is to make a sticky nav using vanilla JavaScript.

The method querySelector is used to target the navigation bar which has an ID of main, this is assigned to the variable nav. The distance between the the nav bar and the top of the window is calculated using the offsetTop property of the element.

A function named fixNav is created with an if…else statement inside it. If the distance that the page has scrolled is greater or equal to the value set in the topOfNav variable two things happen; a class of fixed-nav is added to the body tag and the height of the nav bar is added to the stop of the window to account for it coming out of the flow of the page. If the distance that the page has scrolled is less than value set in topOfNav the class is removed the padding-top is set to 0.

On the css side of things the nav bar with the newly appended class of fixed-nav is given a position of fixed and a subtle shadow.