By the end of this lesson, we will build a sticky nav that:
Hides when you scroll down
Shows up when you scroll up
We do this because every part of a screen is precious real estate.
When users scroll down, they want to read content on your screen. We don’t want the navigation to block content.
When they scroll back up, they may want to navigate elsewhere. If we show the navigation when scrolling back up, they won’t have to scroll up ALL the way!
Scrolling upwards or downwards?
First, we need to detect whether the user is scrolling. We can do this with the scroll event.
The best way to know whether a user is scrolling downwards or upwards is to keep a variable that stores the previous scroll position. We’ll call this prevScrollPos.
If the current scroll position is larger than prevScrollPos, we know we’re scrolling downwards.
If the current scroll position is smaller than prevScrollPos, we know we’re scrolling upwards.
window.addEventListener('scroll', event => {
const scrollPos = window.scrollY
if (scrollPos > prevScrollPos) {
console.log('Scrolling downwards')
} else {
console.log('Scrolling upwards')
}
// Updates prevScrollPos to current value
prevScrollPos = scrollPos
})
The condition I wrote above isn’t 100% accurate. If we want to be strict, there’s still one more condition where scrollPos === prevScrollPos (where we aren’t scrolling).
if (scrollPos > prevScrollPos) {
// Scrolling downwards
} else if (scrollPos < prevScrollPos) {
// Scrolling upwards
} else {
// Not scrolling
}
But in this case, we don’t need to be 100% accurate. Why? Try scrolling upwards and downwards with this accurate statement. You’ll notice the else condition doesn’t trigger at all.
Hiding the nav when scrolling down
To hide <nav> we need to move it upwards. we can do this by setting a negative top value.