Skip to main content Skip to secondary navigation 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);

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