eventListenerSubscriptions
Prefer addEventListener over assigning to on* event handler properties.
✅ This rule is included in the browser logical preset.
Modern DOM event handling should use addEventListener rather than assigning functions directly to on* event handler properties like onclick or onload.
Legacy event handler properties have several limitations:
- They can only hold one function at a time (overwriting previous handlers)
- They don’t provide options for capture phase or passive listeners
- They’re harder to remove later
Using addEventListener provides more flexibility by allowing multiple event listeners for the same event.
Examples
Section titled “Examples”element.onclick = function () { console.log("clicked");};
window.onload = () => { initialize();};
button.onmousedown = handleMouseDown;
form.onsubmit = (event) => { event.preventDefault();};element.addEventListener("click", function () { console.log("clicked");});
window.addEventListener("load", () => { initialize();});
button.addEventListener("mousedown", handleMouseDown);
form.addEventListener("submit", (event) => { event.preventDefault();});Options
Section titled “Options”This rule is not configurable.
When Not To Use It
Section titled “When Not To Use It”If you need to support very old browsers that don’t have addEventListener (Internet Explorer 8 and below), you might need to use event handler properties.
However, for modern web development, addEventListener is the recommended approach.
Further Reading
Section titled “Further Reading”Equivalents in Other Linters
Section titled “Equivalents in Other Linters”
Made with ❤️🔥 in Boston by
Josh Goldberg and contributors.