Alex Ivasyuv
Alex Ivasyuv

Reputation: 8844

How to catch event that was stopPropagation

For example we have a page with a link that has onclick event listener on it. But handler makes stopPropagation. How I can handle that click event was made, if it's not bubble to root anymore?

e.g.

document.addEventListener('click', function(e) {console.log(e);});
a.onclick = function(e) {e.stopPropagation();};

Upvotes: 5

Views: 3110

Answers (2)

user56reinstatemonica8
user56reinstatemonica8

Reputation: 34084

The simple answer is, add a third argument, true, when adding your event listener.

document.addEventListener('click', someFunction, true)

This flag (called useCapture) will call someFunction on all clicks in a document, even when the user clicked inside an element with a click handler that called event.stopPropagation.

With options

If you're already passing an object of options as the third argument, simply include capture: true in them:

document.addEventListener('click', someFunction, { capture: true, ...someMoreOptions })

Why?

Enabling the handler's useCapture mode like this means the listener listens during the earlier "capture" phase of the event (which starts at the outmost element then trickles down through children), instead of the later "bubble" phase (which starts at the innermost element and bubbles back up through ancestors, and is the one stopPropagation blocks).

Side effects

That also means that applying this setting changes the timing: your capture phase click event will occur before any click events of either type inside child or descendant elements.

For example, in the above function, if a user clicks on a button on the page, the someFunction attached to the document's capture phase will be called before any handlers attached to the button; whereas without setting use capture to true, you'd expect it to be called after.

Upvotes: 2

janfoeh
janfoeh

Reputation: 10328

DOM event propagation works in three phases: the capture phase, the target phase and the bubble phase. Roughly, the event first works its way down to the target, reaches the target and then works its way back up.

By default, event handlers are attached in the final bubble phase. If you attach a click event listener in the first capture phase, it will run before the previous handler has had the chance to call stopPropagation.

See this question for a deeper explanation.

Upvotes: 8

Related Questions