5

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();};
Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126
Alex Ivasyuv
  • 8,217
  • 17
  • 67
  • 89
  • What do you want to do exactly? In this case you have to catch the click before the propagation is stopped. If you want to stopPropagation AND notify the document you could trigger a custom event. – donnywals Feb 11 '15 at 12:14
  • 1
    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. If you attach a click event listener in the capture phase, the other event handlers `stopPropagation` should have no effect. See [this question](http://stackoverflow.com/questions/4616694/what-is-event-bubbling-and-capturing) for a deeper explanation. – janfoeh Feb 11 '15 at 12:29
  • Thanks @janfoeh! It's exactly what I was looking for. Please add that as an answer, I'll accept it. `document.addEventListener('click', function(e) {console.log(e);}, true);` – Alex Ivasyuv Feb 11 '15 at 13:21

1 Answers1

8

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.

Community
  • 1
  • 1
janfoeh
  • 10,235
  • 2
  • 30
  • 55