aloescript
aloescript

Reputation: 11

Having trouble fixing "Uncaught TypeError: Cannot read property 'remove' of undefined"- I've consulted other answers

I am trying to implement this bit of code to enable a sticky nav bar on my website: https://www.w3schools.com/howto/howto_js_navbar_sticky.asp

I keep getting the following error: "index.html:44 Uncaught TypeError: Cannot read property 'remove' of undefined"

Here is the snippet:


<body class="is-preload">
        <div class="topnav">
            <a class="active" href="#header">Home</a>
            <a href="#first">Book an Appointment</a>
            <a href="#second">Contact</a>
            <a href="#third">About</a>
            
          </div>
          <script>// When the user scrolls the page, execute myFunction
            
            
            
            
            window.onscroll = function() {myFunction()};
            // Get the navbar
            var navbar = document.getElementsByClassName("topnav");
            
            
            
            
            // Get the offset position of the navbar
            var sticky = navbar.offsetTop;
            
            
            // Add the sticky class to the navbar when you reach its scroll position. Remove "sticky" when you leave the scroll position
            function myFunction() {
              if (window.pageYOffset >= sticky) {
                navbar.classList.add("sticky")
              } else {
                navbar.classList.remove("sticky");
               
              }
            }</script>

I cant figure out for the life of me whats wrong. Its the exact bit of code from the W3C site and it wrks fine there.

Upvotes: 0

Views: 1175

Answers (3)

Mazharul Islam
Mazharul Islam

Reputation: 24

You need the sticky navbar. Just use querySelector instead of getElementsByClassName like as below:

var navbar = document.querySelector(".topnav");

Upvotes: 1

Da Mahdi03
Da Mahdi03

Reputation: 1608

Your getElementsByClassName will return an array of elements and not a single element, so you want to use

document.getElementsByClassName("topnav")[0];

If you only have one element in that class, or you can just switch to an ID as well

Upvotes: 1

dev
dev

Reputation: 841

From glancing at it, it would appear to be because the following part returns an array and you are treating it as an element:

var navbar = document.getElementsByClassName("topnav");

What you are getting is actually an array with the navbar as its first element. Change it to the following and hopefully it should work:

var navbar = document.getElementsByClassName("topnav")[0];

Upvotes: 1

Related Questions