Reputation: 11
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:
once: true
to the option object - this works, but capture doesn'tcapture
with useCapture
- this also doesn't seem to work and in both cases no error/warning messagesonce
- I am using chrome v88 and tried opening the file with Safari too just in case it is a browser-related issueDo 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>
Upvotes: 1
Views: 1480
Reputation: 1296
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>
Upvotes: 1
Reputation: 664970
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>
Upvotes: 2