Use addEventListener when more than one part of an application needs to react to the same event. It registers a callback for an event type on a DOM event target. Unlike assigning an onclick-style property, adding another listener does not overwrite the first, and registration can include options such as capture, passive, and once. section 6.2.13
Choose options and listener placement for the behavior you need:
- Use once: true for a handler that should remove itself after firing. Use passive: true for scroll or touchstart when the handler will not call preventDefault(). section 6.2.13
- Use capture: true to listen as an event travels down toward its target; otherwise, listeners can react as it bubbles back up. A listener on a shared ancestor can handle events from descendants, reducing listener overhead. section 6.2.13 section 6.4
- Keep a reference to a callback that must be removed later: removeEventListener needs the same function reference and compatible options. section 6.2.13
function onScroll() {
console.log(window.scrollY);
}
window.addEventListener("scroll", onScroll, { passive: true });
// ... later
window.removeEventListener("scroll", onScroll);
A named scroll handler can be registered as passive and later removed using that same function reference. section 6.2.13
Custom elements use the same API at their public boundary. An element can dispatch a CustomEvent with data in detail; consumers listen on the element and read that data from the event. Set bubbles when the event should travel up the DOM tree and composed when it should cross a shadow boundary. React-style event attributes on a custom tag are not a substitute for this standard listener API. section 7.11
<script type="module" src="star-rating.js"></script>
<p>Flight rating: <star-rating value="4"></star-rating></p> #1
<p>Hotel rating: <star-rating value="2"></star-rating></p> #1
<p>Restaurant rating (editable):
<star-rating editable id="restaurant-rating"></star-rating> #2
</p>
<script>
document.getElementById("restaurant-rating").addEventListener("change", e => {
console.log(`New rating: ${e.detail.value}`); #3
})
</script>
A consumer listens for a rating element’s change event and reads the selected value from e.detail. section 7.11


