I have a class that represents action to be applied to a fullscreen menu element this.menu.
Looks like this (most of the code omitted). Key point is clickOutsideHandler listener that will check if this.menu contains the event target node: if not, menu should be closed:
class Menu {
clickOutsideHandler = e => {
if (!this.menu.contains(e.target)) {
this.close();
}
};
open() {
// Apply style changes
// Add an event listeners
document.addEventListener('click', this.clickOutsideHandler);
}
close() {
// Revert style changes...
// Remove event listeners
document.removeEventListener('click', this.clickOutsideHandler);
}
}
The problem here is that this.clickOutsideHandler is added "too fast" and even the trigger click get's intercepted by the listener, before actually show the menu:
document.querySelectorAll('[data-menu-trigger]').forEach(trigger => {
trigger.addEventListener('click', e => {
e.preventDefault();
// Call open() on the menu instance
menu.open();
});
});
A small timeout before adding the event listener would solve the problem. What other options do I have?