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

84 thoughts on “Run a Javascript function when clicking outside div1 AND div2”

Leave a Comment