Skip to main content Accessibility Feedback

WTF is `use capture` in vanilla JS event listeners?

A few weeks ago, I shared an approach to writing event listeners known as event bubbling.

The last argument in addEventListener() is useCapture, and it specifies whether or not you want to “capture” the event. For most event types, this should be set to false. But certain events, like focus, don’t bubble.

Setting useCapture to true allows you to take advantage of event bubbling for events that otherwise don’t support it.

// Listen for all focus events in the document
document.addEventListener('focus', function (event) {
    // Run functions whenever an element in the document comes into focus
}, true);

Update: Not sure when to actually use use capture? Here’s how to figure it out.


🚀 Make 2018 the year you master JavaScript! My pocket guides and mini courses are short, focused, and made for beginners. You can do this!

Have any questions or comments about this post? Email me at chris@gomakethings.com or contact me on Twitter at @ChrisFerdinandi.

Get Daily Developer Tips