11

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?

Anusha Nilapu
  • 1,243
  • 8
  • 24
  • 36

2 Answers2

13

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>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
-4

You should pass false as the third argument to the function addEventListener(). This disables the event capturing stage.

document.body.addEventListener('click', onClickFunc, false);
Pi Da
  • 359
  • 2
  • 8
poltorin
  • 284
  • 1
  • 4
  • 13