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

  1. Attach a basic click handler: javascript const btn = document.querySelector("#submit"); btn.addEventListener("click", (event) => { console.log("Clicked!", event.target); });
  2. Use the once option to auto-remove after firing: javascript btn.addEventListener("click", handler, { once: true });
  3. Use capture to handle events during the capture phase: javascript document.body.addEventListener("click", handler, true);
  4. Mark scroll/touch listeners as passive for better performance: javascript window.addEventListener("scroll", onScroll, { passive: true });

Tips

  • Always remove listeners with removeEventListener when 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.
  • this inside an arrow function listener refers to the outer scope, not the element; use a regular function if you need this to be the target.