简体   繁体   中英

Run a Javascript function when clicking outside div1 AND div2

Trying to run a Javascript function only if click outside div1 AND div2 . If clicked inside div1 or div2, nothing should happen. Any idea how I could achieve that? Example: I would need div2 to be set display: none and additionally add styles to div1 when clicked outside the divs.

 var x = document.getElementById("mega-menu"); document.addEventListener('mouseup', function(e) { if (.(x.contains(e.target) || document.getElementById("menu-item-136").contains(e.target))) { x.style;display = 'none'. var elem = document;querySelectorAll("#menu-item-136"). elem.forEach((elem) => { elem.style;backgroundColor = "red"; }); } });

This is the furthest I could get. But at the moment, div2 (mega-menu) also gets hidden when clicked on the menu item... Hope you understand what I mean...

Thanks

Can you complete your sample code above? I've added elements to your snippet, but can't duplicate your problem. It seems to be working for me.

Also a couple of off-topic best practices:

  • the HTML standard doesn't allow for elements with duplicate IDs. If you have more than one element with id #menu-item-136 , you should be using a class instead of an ID.
  • Get both elements outside the event listener...more efficient (like you're already doing with #mega-menu )
  • Instead of having an if statement with a nested block, do an if...return instead. That way your code is less indented.

 var x = document.getElementById('mega-menu'); var y = document.getElementById('menu-item-136'); document.addEventListener('mouseup', function(e) { if (x.contains(e.target) || y.contains(e.target)) return; x.style.display = 'none'; y.style.backgroundColor = 'red'; });
 div { border: 1px solid black; }
 <div id='mega-menu'>mega menu</div> <div id='menu-item-136'>menu 136</div>

Looks like from this code,

document.querySelectorAll("#menu-item-136");

There are multiple elements with id "menu-item-136" as you are looping through the result.

First of all If there are multiple elements with same Id, It is not a valid HTML.

Thats why

document.getElementById("menu-item-136").contains(e.target)

this results in false, as it may have selected wrong element other that what you have clicked.

Even if you use class to get the elements, it may still fail as querySelector based on class will still results in returning multiple elements.

Instead of checking if your target element is contained in the div's - use a check to see if the element parent hierarchy have class name that you add for menu-item div.

if( e.target.closest(".container-class"))

So now you are just checking if current target have any parent with menu-item's class.

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