Hey there! I've been working on creating a sticky navbar using vanilla JavaScript. My goal is to make the logo and navbar stay sticky when scrolling, but unfortunately, I'm running into some errors that I can't seem to fix. I would really appreciate it if someone could take a look at the code below and help me out. Thank you!
let nav = document.querySelector('.nabar');
let topToNav = nav.offsetTop;
let logo = document.querySelector('.logo');
function stickyNav () {
if(window.scrollY >= topToNav) {
logo.style.paddingTop = nav.offsetHeight + 'px';
logo.classList.add('fixed');
} else {
logo.style.paddingTop = 0;
logo.classList.remove('fixed');
}
}
window.addEventListener('scroll', stickyNav);
.nabar{
background-color: darkslategrey;
padding: 15px 0px;
}
.nabar li{
list-style: none;
display: inline;
font-size: 20px;
padding: 0px 15px 0px 15px;
}
.nabar ul {
text-align: center;
}
.nabar a:hover {
text-decoration:none;
color: white;
}
.nabar a{
color: white;
}
.fixed .nabar {
position: fixed;
width: 100%;
top: 0;
left: 0;
box-shadow: 0 3px 6px rgba(black, .3);
}
.test{
height: 600px;
background: yellow;
}
.test2{
height: 609px;
background: green;
}
.logo{
height: 100px;
}
.logoimg{
width: 240px;
height: 100px;
margin: 0 auto;
display: block;
}
<div class="logo">
<img class="logoimg" src="http://pngimg.com/uploads/car_logo/car_logo_PNG1648.png">
</div>
<div class="nabar">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">Features</a></li>
<li><a href="#">Portfolio</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact Us</a></li>
</ul>
</div>
<div class="test">
</div>
<div class="test2">
</div>