• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

405
Views
JS Mobile Menu Error: Cannot read properties of null

The mobile menu does not close due to this error:

Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')

Here is the JS:

//MOBILE MENU TOGGLE//

var menu_element = document.getElementById('menu-mobile-open');

var menu_exists = !!menu_element;

if(menu_exists){

    menu_element.addEventListener('click', function(){

        document.body.classList.add('menu-mobile-active');

    });


    document.getElementById('menu-mobile-close').addEventListener('click', function(){

        document.body.classList.remove('menu-mobile-active');

    });

}
about 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can simplify your code, and instead of adding and removing class on click events, you can toggle that class. A sample example for menu button toggle -

let menu = document.getElementById("menu-button");

menu.addEventListener("click", function(){
    menu.classList.toggle("active");
})

On each click, active class will be toggled. If it is present, then it will be removed. If it is not present, then it will be added.

In this case, all you need to make sure is that the menu button's id matches with the id that you're fetching in JavaScript. You do not need to check for it's existence/visibility on website, it doesn't seem necessary to me, as event listener will apply only when it exists anyway.

about 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error