How to use addEventListener in JavaScript
· Category: JavaScript
Short answer
addEventListener attaches a callback to an element for a specific event type, supporting options like once, capture, and passive for fine-grained control.
Steps
- Attach a basic click handler:
javascript const btn = document.querySelector("#submit"); btn.addEventListener("click", (event) => { console.log("Clicked!", event.target); }); - Use the
onceoption to auto-remove after firing:javascript btn.addEventListener("click", handler, { once: true }); - Use
captureto handle events during the capture phase:javascript document.body.addEventListener("click", handler, true); - Mark scroll/touch listeners as
passivefor better performance:javascript window.addEventListener("scroll", onScroll, { passive: true });
Tips
- Always remove listeners with
removeEventListenerwhen components unmount to prevent memory leaks. - Use named functions instead of anonymous arrows if you need to detach the listener later.
Common issues
- Attaching the same listener multiple times causes duplicate firing.
thisinside an arrow function listener refers to the outer scope, not the element; use a regular function if you needthisto be the target.