简体   繁体   中英

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?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM