How to stop event capturing in javascript?
Asked Answered
A

2

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?

Acoustician answered 4/9, 2018 at 9:54 Comment(0)
C
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>
Chronicle answered 4/9, 2018 at 10:0 Comment(0)
C
-5

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

document.body.addEventListener('click', onClickFunc, false);
Crossrefer answered 4/9, 2018 at 10:4 Comment(1)
this is introduced by google as a spoiling commonly used method codeZerla

© 2022 - 2024 — McMap. All rights reserved.