Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

129
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!