In short, I have addEventListener
inside of addEventListener
. The event I'm listening to is click
. Here's an example of my code:
function toggleElement() {
// function stuff
}
anchor.addEventListener('click', (e) => {
e.preventDefault();
if (!anchorWrapper.classList.contains('active')) {
// do some stuff
window.addEventListener('click', toggleElement, false);
} else {
// do some stuff
window.removeEventListener('click', toggleElement, false);
}
});
Every time the anchor element is clicked, I assign an event listener to the window which listens to clicks. I'd expect the user to click the anchor, which in turn SHOULDN'T initialize toggleElement
, but just assign a event listener to the window. Then, according to my thinking (which turns out to be wrong), the function should only be initialized on the next, second click anywhere on the window. However, it get's run on the click on the anchor element.
What am I not getting right? How can I prevent the toggleElement
function to not be initialized when a user clicks on the anchor element, but instead wait for click
events on the window?