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

128
Visualizações
How to disallow click function when current class is inactive with JavaScript?

When in mobile view, the hamburger menu appears and the user clicks the icon it opens, when you click the close icon. its closes.

I'm attempting to allow users to click outside of the menu to close the menu. Unfortunately the JS code provided above, Allows users to click Anywhere on the site, to Open & close the menu. I Don't want this, I just want the menu to be closed when a user clicks outside of it.

How can I achieve this? Any help is appreciated.

document.querySelector('#bg-close').addEventListener('click', function() {
    document.querySelector('.nav').classList.toggle('nav-container')
})

The issue I'm attempting to solve is on my website

Summary:

Hamburger menu is being activated with a click anywhere on the site.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can implement something like below:

It uses an if statement to see if the .nav-open class is active, in case is not there, nothing will happen. In opposite case it will be removed.

$('#bg-close').on('click', function() {
    let nav =  $('#navElement-id');
    if(nav.attr('class') == 'nav-container nav-open'){
       nav.attr('class','nav-container');
    }
});
*{padding:0;margin:0}
#bg-close{height:100vh;width:100vw;background-color:blue}
.nav-container{color:blue; padding:10px;position:absolute;top:10px; left:0;}
.nav-open{color:black!important;background-color:grey;width:300px;height:200px}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="bg-close">
</div>
<div id="navElement-id" class="nav-container nav-open">Click on the blue</div>

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