简体   繁体   中英

Event listener and button click conflict

I have a menu that needs to obey the following behavior:

  • Open with an external button press
  • Close when there is a click outside it's boundaries

The problem is, that the button to open is also outside the boundaries of the menu and so currently, the button press is opening the editor menu, and then the click listener is immediately closing it again. I've tried using variables and element data so that the click listener only activates if the menu is already open, but the event listener is slower than the button click and so the menu has already been expanded (as far as the listener knows) by the time it is activated. I know I can solve this using timeout so the data isn't changed to "expanded = true" until after the click listener has activated, but this seems kind of clunky and I'm wondering if there is a better option. Here is a code snippet to demonstrate the problem.

And the js code that accompanies it:

document.addEventListener("click", (event) => {
  if (!document.getElementById("menu").contains(event.target) && document.getElementById("menu").dataset.open) {
    closeMenu();
  }
});

//Expand menu
function openMenu() {
  document.getElementById("menu").dataset.open = true;
  document.getElementById("menu").style.height = "80vh";
  console.log("open");
}
//Collapse menu
function closeMenu() {
  document.getElementById("menu").dataset.open = false;
  document.getElementById("menu").style.height = "0";
  console.log("close");
}

Thanks for your help!

You can have the button prevent its parent element from registering the click by taking the event parameter in openMenu, and calling the stopPropogation method on it.

function openMenu(e) {
  e.stopPropogation()
  document.getElementById("menu").dataset.open = true;
  document.getElementById("menu").style.height = "80vh";
  console.log("open");
}

How do I prevent a parent's onclick event from firing when a child anchor is clicked?

Thanks for the answers: Here's my solution based on @Addison Schmidt's answer that fixes a couple of errors:

function openMenu(e) {
  if (!event) var e = window.event
  e.cancelBubble = true;
  if (e.stopPropagation) e.stopPropagation();

  document.getElementById("menu").dataset.open = true;
  document.getElementById("menu").style.height = "80vh";
  console.log("open");
}

Source: Event.stopPropagation Not Working

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