Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

535
Vistas
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 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

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 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda