Add click event after another click event

Alexander Weihmayer picture Alexander Weihmayer · Oct 21, 2015 · Viewed 14.6k times · Source

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?

Answer

guest271314 picture guest271314 · Oct 21, 2015

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>