Hide a navbar when the user starts to scroll the page using javascript
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
margin: 0;
background-color: orange;
font-family: Arial, Helvetica, sans-serif;
}
#navbar {
background-color: #333;
position: fixed;
top: 0;
width: 100%;
display:block;
transition: top 0.3s;
}
#navbar a {
float: left;
display: block;
color: red;
text-align: center;
padding: 15px;
text-decoration: none;
font-size: 17px;
}
#navbar a:hover {
background-color: green;
color: orange;
}
</style>
</head>
<body>
<div id="navbar">
<a href="#home">Home</a>
<a href="#news">News</a>
<a href="#news">About Us</a>
<a href="#news">Contact Us</a>
<a href="#news">Sitemap</a>
</div>
<div style="padding:15px 15px 2500px;font-size:30px;margin-top:30px;">
<p><b>This example demonstrates how to hide a navbar when the user starts to scroll the page.</b></p>
<p>Scroll down this frame to see the effect!</p>
<p>Scroll up to show the navbar.</p>
</div>
<script>
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;
}
</script>
</body>
</html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
margin: 0;
background-color: orange;
font-family: Arial, Helvetica, sans-serif;
}
#navbar {
background-color: #333;
position: fixed;
top: 0;
width: 100%;
display:block;
transition: top 0.3s;
}
#navbar a {
float: left;
display: block;
color: red;
text-align: center;
padding: 15px;
text-decoration: none;
font-size: 17px;
}
#navbar a:hover {
background-color: green;
color: orange;
}
</style>
</head>
<body>
<div id="navbar">
<a href="#home">Home</a>
<a href="#news">News</a>
<a href="#news">About Us</a>
<a href="#news">Contact Us</a>
<a href="#news">Sitemap</a>
</div>
<div style="padding:15px 15px 2500px;font-size:30px;margin-top:30px;">
<p><b>This example demonstrates how to hide a navbar when the user starts to scroll the page.</b></p>
<p>Scroll down this frame to see the effect!</p>
<p>Scroll up to show the navbar.</p>
</div>
<script>
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;
}
</script>
</body>
</html>
Result: