How to stop event capturing in javascript?

Anusha Nilapu picture Anusha Nilapu · Sep 4, 2018 · Viewed 8.2k times · Source

We can use event.stopPropagation() for stopping event bubbling. Can we use same method for stopping event capturing also?

If no how can we achieve it?

Answer

CertainPerformance picture CertainPerformance · Sep 4, 2018

If a listener has been added to the capturing phase, rather than the bubbling phase, then you can prevent the event from capturing down to child elements with the same method: event.stopPropagation().

For example, in this code, you'll see that #inner's listener is never triggered, because #outer's listener stops the event from propagating downward:

document.querySelector('#outer').addEventListener(
  'click',
  function(event) {
    console.log('propagation stopped');
    event.stopPropagation();
  },
  true // Add listener to *capturing* phase
);

document.querySelector('#inner').addEventListener(
  'click',
  function(e) {
    console.log('inner clicked');
  }
);
<div id="outer">
  outer
  <div id="inner">
    inner
  </div>
</div>