2

My goal is, when user pass my first section(#video-section), I want to close my side menu.

This is my code:

// When the user scrolls the page, execute myFunction 
window.onscroll = function() {
    var video = document.getElementById("video-section");
    var menubar = document.getElementsByClassName("menubar");
    var drawer = document.getElementsByClassName("drawer");

    var videoheight = video.offsetHeight;
    console.log("Scroll amount:" + window.pageYOffset);
    console.log("Video section amount:" + videoheight)

    if (window.pageYOffset == videoheight) {
        console.log("Passed");
        menubar.classList.remove("open");
    }
};

I get the following error message at the classList.remove() function call:

Uncaught TypeError: Cannot read property 'remove' of undefined at window.onscroll

Krisztián Balla
  • 19,223
  • 13
  • 68
  • 84
Tugce Aksoz
  • 51
  • 2
  • 15
  • 3
    [`document.getElementsByClassName`](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName) returns a [`HTMLCollection`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection) Which doesn't have a property called `classList`, so it's undefined. – Spencer Wieczorek Aug 18 '18 at 08:03

3 Answers3

1

getElementsByClassName() returns an array of nodes and not a single node.

The getElementsByClassName() method returns an array of all the nodes that contain that particular class provided as a string in its parameter. You can do the following to make it correct:

  1. Provide an id attribute to your menubar and use getElementById to get that particular node.
  2. Or, do menubar[0].classList.remove("open"); to remove the class from the first matched element node.
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
UtkarshPramodGupta
  • 7,486
  • 7
  • 30
  • 54
0

well because the menubar is not an object but an HTMLCollection and classList for that is undefined heres what you can do: var menubar = document.querySelector('.menubar'); which then you would be able to change it's style and classList of. hope it works well for you:)

sinawic
  • 157
  • 3
  • 14
0

classList is a read only property that exists on an element itself and not on the result of getElementsByClassName method, which is a collection .

VigSank
  • 62
  • 8