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

135
Visualizações
Bind click event to all elements except two

I have a menu and a button to toggle this menu:

<a id="openMenu" onclick="openMenu()">Menu</a>
<div class="menu">..menu stuff..</div>

Now I want to bind a click event on the whole <body>, except the two described elements. The click event is, that when the <menu> is visible and the user clicks anywhere inside the <body> the <menu> should close again.

I have the following code for this:

var menuComponents = $(".menu, #openMenu").children();
  $("body")
    .not(menuComponents)
    .on("mousedown", function (event) {
      if ($(".menu").attr("active") == "true") {
        setActive(".menu");
      }
    });

But now when the menu is opened and I click on the <a id="openMenu"...> button to close the menu again, it is closed and immediately opened again. So, is it possible to exclude the menu and openMenu button from the body?

Are there any hints on why this behavior is so?

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

0

Add listener to body then if the clicked element (e.target) is the link .toggle() the menu -- otherwise any other click will default to closing the menu.

BTW, there are some things you shouldn't do (especially if you use jQuery).

  • Inline event handlers are garbage, so don't use them.

  • #id just hinder your ability to update and expand your code, so use classes. There are a few times when #id might be necessary but no with the present situation.

     <a /*id*/="useClassNotID" /*onclick="DoNotUse(this)"*/>Menu</a>
    

$(document).click(function(e) {
  if ($(e.target).is('.openMenu')) {
    $('.menu').toggle({
      duration: 500
    });
  } else {
    $('.menu').hide({
      duration: 500
    });
  }
});
<a href='#' class="openMenu">Menu</a>
<section class="menu">
  <ul>
    <li><a href='#'>Link</a></li>
    <li><a href='#'>Link</a></li>
    <li><a href='#'>Link</a></li>
    <li><a href='#'>Link</a></li>
    <li><a href='#'>Link</a></li>
  </ul>
</section>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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