简体   繁体   中英

Trigger Javascript click/touch event only if NO other events are simultaneously triggered?

I'm trying to make a navigation menu which is hidden from view but that which appears by touching/clicking on the screen.

The problem I see is that touching/clicking many places on the screen could open the navigation menu while simultaneously triggering an event on whatever button, link, etc. that might have been in the vicinity.

So far, I'm trying to handle this with a :not clause in jQuery. Unfortunately there is something not work with the :not clause as the toggling happens regardless of where you click within the body .

HTML:

<div id="NavigationMenu">i'm the navigation menu</div>
<div class="icon-reorder">toggle</div>
<div id="main_content">i'm the main content
  <button type="button">button</button>
</div>​

JS:

$(document.body).on('click', ['body:not(".btn, a, i, button, input, textarea")', '.icon-reorder'], function(){
    console.log('clicked');
    $('#NavigationMenu').toggle();
    $('#main_content').toggle();
});

$('button').on('click', this, function(){
   console.log('button clicked');
});

Might someone be able to help with this code? Or is this even the right way to go about solving this problem? It looks a little hack-ish to me.

This navigation menu is the main one for my site so having an annoying UI/UX (nav opens too much/too little) is a deal breaker. I mainly interested in touch compatible code but any and all UI/UX suggestions would be welcome...

Instead of using a :not clause, why not use event delegation (which, I only learned two months ago, is a fancy term for handling the events with a callback, on a parent element)

$(body).on("click", function(event) {
  if(event.target.type !== "button" && <whatever other conditions>) {
       <toggle menu>
  }
});

Here's an updated Fiddle . I'm logging the click event object to the console so you can look at event.target and see if there's anything more suited to your needs to compare to

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