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

131
Vistas
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 Respuestas
Responde la pregunta

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 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