Can't get Dropdown Menu to close

Hi everyone. Currently doing challenge: “Build a Technical Documentation Page”.

I’ve finished HTML and CSS and I’m happy with that. It passes all tests.

However, I’m having trouble with Javascript. Haven’t done the Javascript course yet.

My goal: On screen-sizes with a width of <=1365, I want to close the drop-down menu when the user clicks a link in the menu.

However, I’m unable to do it because I keep getting this error:

Uncaught TypeError: listener.addEventListener is not a function
at window.onload (documentation.js:13)

Here is my Javascript code:

var readyState = document;

if (readyState = "complete") {
    if (window.innerWidth <= 1365) {

        function off () {
            subMenu = "off";
        }

        window.onload = function() {
            var subMenu = document.getElementById("toggle-mobile-menu").value;
            var listener = document.getElementsByClassName("nav-link");    
            listener.addEventListener('click', off);
    }
}
}

Here is my Codepen for the Project: https://codepen.io/xarmar/pen/rNjJjXK

Thanks in advance.

1 Like

maybe use querySelector instead of the getElement(s)By...
the getElementsByClassName returns an array-like thing, a list of all elements with that class name from which you need to get the one you want

querySelector gives back the first element that matches the css selector you put in it

1 Like

Thank you. I was able to fix it.

For reference, if it can help anyone in the future this is how I change the Js Code.

New Code:

var readyState = document;

if (readyState = "complete") {
    if (window.innerWidth <= 1365) {

        function off () {
            var chkBox = document.getElementById('toggle-mobile-menu');
            if (chkBox.checked)
            {
                chkBox.checked=false;
            }
        }

        window.onload = function() {
            var listener = document.querySelector("#main-menu");    
            listener.addEventListener('click', function () {
                off();
            })
    }
}
}
1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.