I am trying to add a click event to the document in another click event attached to a button. However, the second click event is fired right away as if the event overlaps. I looked into stopping propagation, using a timeout, removing the listener, preventDefault()
, but I've had no success.
This is an example of what I am trying to do.
document.getElementById("test").addEventListener('click', first);
function first(){
document.addEventListener('click', second);
}
function second(){
alert("I'm not suppose to appear after the first click, only the second.");
}
For testing, I am using a simple button
<button type="button" id="test">Click</button>
I am doing this without JQuery. Is this possible?
Try using event.stopImmediatePropagation()
document.getElementById("test").addEventListener('click', first);
function first(e){
e.stopImmediatePropagation();
this.removeEventListener("click", first);
document.onclick = second;
}
function second(){
alert("I'm not suppose to appear after the first click, only the second.");
}
<button type="button" id="test">Click</button>