Jordan H
Jordan H

Reputation: 55845

Attaching click event listener in onclick immediately calls that event listener

I am attaching a click event listener to the document after the user clicks on a specific element on the page. However, this event listener is immediately called after the onclick function is called which is undesirable. It seems to be using the same click event for both onclick and the just added document click listener.

How can I ensure the event listener I add to the document does not get called until the next click occurs?

document.getElementById('someID').onclick = function(e) {
    document.addEventListener('click', myDocClickListener);
    return false; //handled click
}

function myDocClickListener(e) {
    //...
    //should only be called for future clicks not the one that just occurred in the above function
}

Upvotes: 1

Views: 2982

Answers (2)

Mahesh
Mahesh

Reputation: 31

JLRishe's answer is correct, but if you don't want to do stopPropagation for some reason, you can add event listener in the next event loop:

document.getElementById('someID').onclick = function(e) {
    setTimeout(
      () => document.addEventListener(
        'click',
        myDocClickListener
      ),
      0
    );
    return false; // only needed for <a> 
};

Upvotes: 0

JLRishe
JLRishe

Reputation: 101748

This is happening because of event bubbling. You need to stop the bubbling in your handler:

document.getElementById('someID').onclick = function(e) {
    e.stopPropagation();
    document.addEventListener('click', myDocClickListener);
    return false; //handled click
};

You will probably also need to keep track of whether you have attached the handler yet, so you don't end up attaching it twice if someID is clicked twice.

And unless this handler is on an a element, you don't really need to return false.

Upvotes: 5

Related Questions