Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

527
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda