Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop event capturing in javascript?

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?

like image 984
Anusha Nilapu Avatar asked Sep 04 '18 09:09

Anusha Nilapu


1 Answers

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>
like image 137
CertainPerformance Avatar answered Nov 05 '22 04:11

CertainPerformance