In this tutorial we will see how to Hide and Show Navbar On Scroll With JavaScript. JavaScript Window pageYOffset property is used with CSS position property and transition property to hide and show the Navbar on scroll up and down.
Table of Contents
HTML Code
Take a look at the HTML code given below, it has a main container of menu with class and id named menu. Three links made with anchor tags are also used in this example.
<div class="menu" id='menu'>
<a href="#">Home</a>
<a href="#">About</a>
<a href="#">Contact</a>
</div>
CSS Code
CSS code is given below, In this code position: fixed; is used to fix the position of the Navbar. This position will be changed on scroll with the help of JavaScript code.
CSS transition property is also used to make the transition smooth. In this example the code will take 1 second to hide and show the Navbar.
<style>
*
{
margin: 0;
padding: 0;
}
body
{
font-family: monospace;
height: 2000px;
background-color: #FCEC5E;
}
.menu
{
position: fixed;
background-color: #444;
text-align: center;
width: 100%;
transition: 1s;
}
.menu a
{
display: inline-block;
color: #eee;
text-decoration: none;
font-size: 20px;
padding: 20px 10px;
}
.menu a:hover
{
background-color: #000;
}
</style>
JavaScript Code
Take a look at the JavaScript Code given below, Window pageYOffset property is used in this code.
window.pageYOffset returns the number of pixel the document has been scrolled vertically.
This value is in pixels, it is used in this example to decide whether to hide or show the Navbar.
If value of scroll is greater than 50px, the Navbar will be hidden slowly by the JavaScript code. This is done by changing it's top position to 63px, which is height of our Navbar in this example. This value is used to hide the Navbar completely.
On scroll up, as soon as the value of window.pageYOffset reaches 50 or it is less than 50, the Navbar will reappear.
getElementById() method is used to select or target the Navbar, while .style property is used to change it's top position.
<script>
window.onscroll = function()
{
var pos = window.pageYOffset;
if(pos > 50)
{
document.getElementById('menu').style.top = "-63px";
}
else
{
document.getElementById('menu').style.top = "0";
}
}
</script>
Demo
Video Tutorial
Watch our video tutorial on how to Hide and Show Navbar On Scroll With JavaScript.