What is addEventListener?
target.addEventListener(type, listener, options) registers a function to run when an event of that type happens on a DOM element, document, window or any other EventTarget; you can add many listeners for the same event.
Options
once: true: run the listener a single time, then remove it automatically.passive: true: promise not to callpreventDefault(). Browsers can then scroll immediately, which makestouchstart,touchmoveandwheellisteners smoother.capture: true: listen in the capture phase instead of the bubble phase.signal: anAbortSignal; callingcontroller.abort()removes every listener registered with it. This is the cleanest way to clean up many listeners at once (for example when a component unmounts).
Removing listeners
removeEventListener(type, sameFunction, sameCaptureFlag) needs the exact same function reference, so inline arrow functions cannot be removed. Keep a reference, or use signal.
Compared to onclick
element.onclick = fn holds only one handler; assigning again replaces it. addEventListener supports multiple handlers and the options above.
Inside the listener
event.target(origin) vsevent.currentTarget(the element the listener is on).event.preventDefault()stops default behaviour (form submit, link navigation).- With a normal function,
thisiscurrentTarget; with an arrow function, useevent.currentTarget.
Custom events
target.dispatchEvent(new CustomEvent("cart:add", { detail: {...} })) lets parts of your app communicate through the DOM.
Code example
1document.body.innerHTML = `<button id="save">Save</button> <a id="link" href="https://example.com">Link</a>`;2const save = document.getElementById("save");3const log = [];45// Multiple listeners on the same event6save.addEventListener("click", () => log.push("validate"));7save.addEventListener("click", () => log.push("save"));89// once: removed automatically after the first run10save.addEventListener("click", () => log.push("first-click analytics"), { once: true });1112save.click();13save.click();14console.log(log); // ["validate", "save", "first-click analytics", "validate", "save"]1516// Remove many listeners at once with an AbortController17const controller = new AbortController();18window.addEventListener("resize", () => {}, { signal: controller.signal });19document.addEventListener("keydown", () => {}, { signal: controller.signal });20controller.abort(); // both removed2122// preventDefault: stop link navigation23document.getElementById("link").addEventListener("click", (e) => {24 e.preventDefault();25 console.log("navigation prevented for", e.currentTarget.href);26});27document.getElementById("link").click();2829// Custom events30document.addEventListener("cart:add", (e) => console.log("added to cart:", e.detail.sku));31document.dispatchEvent(new CustomEvent("cart:add", { detail: { sku: "A1" } }));
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.