I'm making a fixed navigation bar and using JavaScript to detect when the user scrolls on the page.
But I'm facing a problem, the console is telling me that the variable navbar is null, after that, as soon as I try to scroll down, it starts constantly generating the same error: Uncaught TypeError: navbar is null
I really don't know what's happening so any help is appreciated, cheers.
window.onscroll = function() {
myFunction()
};
var navbar = document.getElementById("topNav");
var sticky = navbar.offsetTop;
function myFunction() {
if (window.pageYOffset >= sticky) {
navbar.classList.add("sticky");
} else {
navbar.classList.remove("sticky");
}
}
/*testing only*/
body {
height: 500vh;
}
.topnav {
background-color: #333;
overflow: hidden;
}
.sticky {
position: fixed;
top: 0;
width: 100%
}
.topnav a {
float: left;
color: #F72585;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
}
.topnav a:hover {
background-color: #ddd;
color: black;
}
.topnav a.active {
background-color: #F72585;
color: white;
}
.topnav-right {
float: right;
}
<div id="topNav" class="topnav">
<a id="spaceStyle" class="active" href="#home" onclick="spaceChange()">SPACE</a>
<a id="cyberStyle" href="#news" onclick="cyberChange()">CYBER-PUNK</a>
<div class="topnav-right">
<a id="creditsStyle" href="#about" onclick="credistsChange()">About</a>
</div>
</div>