Why is capture option not working in addEventListener

1.1k Views Asked by At

My capture option doesn't seem to be working in the addEventListener, it gives me the same console results whether I set it to true or false.

I checked the following:

  1. Add once: true to the option object - this works, but capture doesn't
  2. Replace capture with useCapture - this also doesn't seem to work and in both cases no error/warning messages
  3. I read online that some (older e.g. chrome version less than 55) browsers don't support newer options such as once - I am using chrome v88 and tried opening the file with Safari too just in case it is a browser-related issue

Do you know what I am doing wrong?

function handleClick(e) {
  console.log(this.classList.value);
}
const divs = document.querySelectorAll('div');
divs.forEach(div => div.addEventListener('click', handleClick, {capture: true}));
.one {
  width: 200px;
  height: 200px;
  background-color: green;
}

.two {
  width: 150px;
  height: 150px;
  background-color: blue;
}

.three {
  width: 100px;
  height: 100px;
  background-color: red;
}
<div class="one">
  <div class="two">
    <div class="three">
    </div>
  </div>
</div>

2

There are 2 best solutions below

1
Bergi On

Your code works just fine for me:

function handleClick(e) {
  console.log(this.classList.value);
}
const divs = document.querySelectorAll('div');
divs.forEach(div => div.addEventListener('click', handleClick, {
  capture: div.classList.contains('capture')
}));
<div class="one capture">
  One
  <div class="two capture">
    Two
    <div class="three capture">
      Three
    </div>
  </div>
</div>

<div class="one bubble">
  One
  <div class="two bubble">
    Two
    <div class="three bubble">
      Three
    </div>
  </div>
</div>

1
Alexis Diel On

He worked for me, maybe you see the same results, that's right, but the capture change the order of it.

If you use capture: true the output is:

one two three

if capture: false, the output is:

three two one

function handleClick(e) { console.log(this.classList.value);}

const divs = document.querySelectorAll('div');

divs.forEach(div => div.addEventListener('click', handleClick, {capture: false}));
main div {
    height: 100px;
    background-color: red;
}
<main>
  <div class="one">
    <div class="two">
      <div class="three">
      </div>
    </div>
  </div>
</main>