1

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>
Steven Selolo
  • 99
  • 1
  • 7
DrFaraday
  • 67
  • 1
  • 11
  • The javascript probably is executed before the DOM is rendered. Try wrapping it in a function and execute onload. ([See this answer](https://stackoverflow.com/questions/4842590/how-to-run-a-function-when-the-page-is-loaded) – Michel Dec 07 '20 at 10:24
  • Your code works well for me! – s.kuznetsov Dec 07 '20 at 10:29

1 Answers1

1

try to access your elements, after page has completely loaded. something like that:

    window.onscroll = function () { myFunction() };

    window.onload = function () {
        var navbar = document.getElementById("topNav");
        var sticky = navbar.offsetTop;

        function myFunction() {
            if (window.pageYOffset >= sticky) {
                navbar.classList.add("sticky");
            } else {
                navbar.classList.remove("sticky");
            }
        }
    }