How to Hide a Navigation Menu on Scroll Down with CSS and JavaScript

A well-designed navigation menu is crucial for user experience on a website.

However, in some cases, it may take up valuable real estate on the screen and interfere with the content.

This is when hiding the navigation menu on scroll down comes in handy.

In this tutorial, we will show you how to hide a navigation menu on scroll down using CSS and JavaScript.


CSS

The CSS code for hiding the navigation menu on scroll down is relatively simple.

All you need to do is set the position of the navigation menu to fixed and give it a top value of zero.

This way, the navigation menu will always be visible on the screen and will not move when the user scrolls down the page.

nav {
position: fixed;
top: 0;
width: 100%;
}

JavaScript

The JavaScript code for hiding the navigation menu on scroll down is a bit more complex, but still manageable.

To make the navigation menu disappear on scroll down, we need to listen for the scroll event and update the top value of the navigation menu accordingly.

If the user scrolls down, the top value should be set to a negative number, making the navigation menu disappear.

If the user scrolls up, the top value should be set back to zero, making the navigation menu reappear.

var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
var currentScrollPos = window.pageYOffset;
if (prevScrollpos > currentScrollPos) {
document.getElementById("navbar").style.top = "0";
} else {
document.getElementById("navbar").style.top = "-50px";
}
prevScrollpos = currentScrollPos;
}

Note that in the above code, the top value of “-50px” is just an example.

You can adjust it to any value that works best for your website.


Conclusion

Hiding a navigation menu on scroll down is a simple and effective way to improve user experience on your website.

With the CSS and JavaScript code provided in this post, you can easily implement this feature on your own website.

Don’t hesitate to experiment with different values and styles to find the perfect solution for your needs.