JavaScript Fundamentals: The Capture Feature of addEventListener()

preview_player
Показать описание
I've been doing some training on event listeners lately and so I've decided to discuss what I think is a poorly understood feature of addEventListener. That is the useCapture parameter that affects event propagation.

Would you like to help keep this channel going?

Tutorials referred to in this video:

For more resources on JavaScript:

#javascript #AllThingsJavaScriptLLC
Рекомендации по теме
Комментарии
Автор

Very nice. Ran into some code that used this feature and was having a hard time making sense of it all with just the documentation, this video did the trick! Something that was not covered is what happens if you mix and match useCapture as true in some elements and false in others. Found out that all capture events happen first, then all bubbling events. So for example, if the window and content-main div events had useCapture set to true, while all the others had it set to false, the output would be the following:

click handled by window!
click handled by content-main div!
click handled by button!
click handled by center div!
click handled by document!

snoW_
Автор

I'll admit I never knew this was possible. Now I'll consider it as a potential solution in the back of my head. Thanks!!

blakefre
Автор

Would you recommend always using e.stopPropagation()? In most cases the bubbling is not required (most of us don't even think about this when we only need it on the target) and it would eliminate a lot of unnecessary "behind the scenes" execution and make our code more efficient.

tedshapera
Автор

nice. I've never seen use capture. I assume then that event.stopPropagation() while using capture would work the same way but in the reverse order. Gonna try it now.

montazmeahii
Автор

Thanks, but I think you missed the crucial One.

.addEventListener('click', () => console.log('form'), false);
document.querySelector('#div').addEventListener('click', () => console.log('div'), true);
document.querySelector('#p') .addEventListener('click', () => console.log('p'), false);

=> #div > p > #form

robitops
Автор

I’m having an issue with a drop down JavaScript button using addEventListener click event where it takes 2 clicks to show the drop down menu, the first click just selects the button and the 2nd click actually displays the drop down menu. Would you have any insight on how to resolve this?

raba