0

Was reading the Docs in MDN about addEventListener. Then I experimented a bit, ended up with the following code:

const inner = document.querySelector('#inner').addEventListener('click',
  () => {
    console.log('inner');
  }, true);


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

I thought that by setting the third element of addEventListener to true it would stop the event propagation and thus would stop the event bubbling of the inner div.

  • How is this not stopping the bubbling?
  • How do I manage to stop the bubbling?
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Willem van der Veen
  • 33,665
  • 16
  • 190
  • 155
  • To stop bubbling issue you can use event.preventDefault() or event.stopPropagation() – Dhiren Aug 25 '18 at 09:58
  • Possible duplicate of [Unable to understand useCapture parameter in addEventListener](https://stackoverflow.com/questions/7398290/unable-to-understand-usecapture-parameter-in-addeventlistener) – bigless Aug 25 '18 at 10:25

1 Answers1

0


You should use stopPropagation for stopping event bubbling.

As per defined standards, it should be prohibited as it can lead to loopholes.

const inner = document.querySelector('#inner').addEventListener('click',
  (e) => {
    e.stopPropagation();
    console.log('inner');
  });


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