JavaScript 30- Day 24 Study Notes

Day 24 of JavaScript 30 by Wes Bos consisted of making a navigation bar sticking to the top of the page as a user scrolled down the web page. Also, a logo area will slide in from the top-left corner when the scrolling started.

There was a header with a featured image and an H1 heading sitting above the navbar, so the initial scrolling had to account for this space.

const topOfNav = nav.offsetTop;function fixNav(){   if(window.scrollY >= topOfNav) { = nav.offsetHeight + 'px';      document.body.classList.add('fixed-nav');   }else { = 0;      document.body.classList.remove('fixed-nav');   }}

The window.scrollY value accounts for the scroll position on the page. If that value is larger than the top of the navbar position, we used the navbar’s offset height to position it at the top of the page. If this condition is not the case, no padding was indicated and the navbar sits at its original position.

Bos noted we add the new attribute to the body of the page and not the nav element.

In the CSS file, we used two classes to position the nav element. Here is the original class.

nav {   background: black;   top: 0;   width: 100%;   transition: all 0.5s;   position: relative;   z-index: 1;}

And the fixed-nav class. This changed the position from relative to fixed, and added a box-shadow for effect.

.fixed-nav nav {position: fixed;box-shadow: 0 5px rgba0(0, 0,0,0.1);}

I’m getting very familiar with selecting the element and adding event listeners, so I’ve skipped showing the code for that.

Follow my study notes as I progress through JavaScript 30.

Retired physician, writer, aspiring website designer and developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store