Skip to main content Accessibility Feedback

When to use “use capture” in your event listeners

Earlier this month, I wrote about the use capture argument in addEventListenerand what it does.

As my buddy Terry Sutton pointed out, though, I didn’t explain when you actually use it.

ie: set it to false and hope for the best!

So, here’s how you figure it out. #

  1. Visit the Event Reference page on MDN.
  2. Click on the event you want to use.
  3. Under “General info” at the top, look for whether bubbles is set to “yes” or “no.”l

If the event doesn’t bubble and you’ll be listening for events on an element other than the one that will trigger the event, set use capture to true.

An Example #

For example, the blur event happens whenever a link or input loses focus.

If I’m listening for blur on a specific input, I can leave use capture as false.

var someInput = document.querySelector('#my-input');
someInput.addEventListener('blur', function (event) {
    // Do stuff...
}, false);

BUT… if I wanted to listen to all blur events in the document, I would set it to true.

document.addEventListener('blur', function (event) {
    // Do stuff...
}, true);

🚀 I just relaunched my Vanilla JS Pocket Guides with new code examples and real projects to help tie everything you’ll learn together. Check it out.

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