I found a very simple way to make a sticky navigation bar here: https://www.w3schools.com/howto/howto_js_navbar_sticky.asp
My code pretty much mirrors the example except I have a height set on mine:
<div id="navbar">
<a href="#home">Home</a>
<a href="#news">News</a>
<a href="#contact">Contact</a>
</div>
The CSS:
#navbar {
background-color: #333;
height: 145px;
overflow: hidden;
}
#navbar a {
float: left;
display: block;
color: #f2f2f2;
text-align: center;
padding: 14px;
text-decoration: none;
}
.content {
padding: 16px;
}
.sticky {
height: 85px;
position: fixed;
top: 0;
width: 100%;
z-index: 1;
}
.sticky + .content {
padding-top: 145px;
}
The JS:
window.onscroll = function() {myFunction()};
var navbar = document.getElementById("navbar");
var sticky = navbar.offsetTop;
function myFunction() {
if (window.pageYOffset >= sticky) {
navbar.classList.add("sticky")
} else {
navbar.classList.remove("sticky");
}
}
What I wanted to do is have a shorter navbar
only when I scroll down. So, I added a height to my .sticky
class and then I was hoping when I scrolled down then my default height would get overridden by my sticky
class. When I look at the code, the sticky
class gets added after my navbar
ID, which is probably why that doesn’t work.
I don’t know what I need to change to make this happen. Does anyone have any suggestions? I haven’t been able to find an example of this functionality.
Thanks,
Josh