Event Listener Options
You'll learn how to fine-tune event listener behavior using the options parameter in addEventListener().
So far, you've used addEventListener() with just an event name and handler function. But there's an optional third parameter that lets you control how the listener behaves—think of it like choosing different settings on a kitchen appliance rather than just turning it on or off.
The Options Parameter
Instead of just addEventListener('click', handler), you can pass an object with special properties:
element.addEventListener('click', handler, {
once: true,
passive: true,
capture: false
});
Three Key Options
once
When set to true, the listener automatically removes itself after firing once. Perfect for one-time actions like confirming a signup—no need to call removeEventListener() yourself.
button.addEventListener('click', handler, { once: true });
// Handler runs once, then auto-removes
passive
Tells the browser you won't call preventDefault() in this listener. This helps performance, especially for scroll and touch events, because the browser doesn't have to wait to see if you'll cancel the default behavior.
element.addEventListener('scroll', handler, { passive: true });
capture
Controls whether the listener fires during the capturing phase instead of bubbling. You learned about capturing and bubbling phases earlier—this just gives you another way to specify it besides passing true as the third parameter.
element.addEventListener('click', handler, { capture: true });
Key Takeaway: The options parameter in addEventListener() gives you precise control over event behavior—once for auto-removal, passive for performance optimization, and capture for phase selection.