In my attempt to create a navigation bar, I have specific requirements:
- It should start with a large height
- Disappear when scrolled down
- Show a smaller version when scrolling back up
- Expand to full height when fully scrolled to the top
I have managed to achieve this by using a function to hide and show the navigation bar, along with an interval to expand it again when reaching the top. However, I believe there might be a more efficient way to combine these actions. Any suggestions would be greatly appreciated!
HTML
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<header id="navbar" class="navbar">
<a href="#home">Home</a>
<a href="#news">News</a>
<a href="#contact">Contact</a>
</header>
</body>
</html>
JavaScript
var prevScrollpos = window.pageYOffset;
var shrinkHeader = 200;
function tellMeAStory() {
}
window.onscroll = function() {
var currentScrollPos = window.pageYOffset;
if (prevScrollpos > currentScrollPos) {
document.getElementById("navbar").style.top = "0";
} else {
document.getElementById("navbar").style.top = "-200px";
$('.navbar').addClass('shrink');
}
prevScrollpos = currentScrollPos;
}
setInterval(function(){
var scroll = getCurrentScroll();
if (scroll < 10){
$('.navbar').removeClass('shrink');
} else {}
},250)
function getCurrentScroll() {
return window.pageYOffset || document.documentElement.scrollTop;
};
CSS
body {
margin: 0;
background-color: #f1f1f1;
font-family: Arial, Helvetica, sans-serif;
height: 2000px;
}
header {
background-color: #333;
position: fixed;
top: 0;
width: 100%;
display: block;
transition: all 0.3s;
height: 200px;
}
.grow{
height: 200px;
}
.shrink{
height: 50px;
}
#navbar a {
float: left;
display: block;
color: #f2f2f2;
text-align: center;
padding: 15px;
text-decoration: none;
font-size: 17px;
}
#navbar a:hover {
background-color: #ddd;
color: black;
}
JSFiddle