The browser
addEventListener: subscribing to an event
"When this happens here, call that function."
Why it exists
Code on a page has no idea when someone will click, start typing or press Esc. It could ask "clicked yet?" every few milliseconds, but that's wasteful and clumsy. The browser flips it around: you hand it a handler function in advance, and it calls the function at the right moment along with everything it knows about what happened. The code doesn't wait or poll: it reacts. That's the foundation of every interactive interface: buttons, forms, games, keyboard shortcuts.
Where it's used
- Buttons: "Add to cart", "Like", "Show more", "Close".
- Input fields: live search on the
inputevent, form validation on submit. - Keyboard: shortcuts (
Esccloses a dialog,/opens search) viakeydownon document. - The browser itself: window
resize,scroll, the network going away and back (online/offline), an image finishing loading (load).
Syntax
element.addEventListener("type", handler);
element.addEventListener("type", handler, { once: true });
element.removeEventListener("type", sameHandler);Examples
// In a browser this would be a button. EventTarget is its "listening" part, and Node has it too
const button = new EventTarget();
let clicks = 0;
function onClick() {
clicks += 1;
}
button.addEventListener("click", onClick);
button.dispatchEvent(new Event("click"));
button.dispatchEvent(new Event("click"));
clicks; // → 2const bell = new EventTarget();
const log = [];
function ring() {
log.push("ding");
}
bell.addEventListener("ring", ring);
bell.dispatchEvent(new Event("ring"));
bell.removeEventListener("ring", ring);
bell.dispatchEvent(new Event("ring"));
log; // → ["ding"]removeEventListener with the same function, and the bell goes quietconst gift = new EventTarget();
let opened = 0;
gift.addEventListener("open", () => opened++, { once: true });
gift.dispatchEvent(new Event("open"));
gift.dispatchEvent(new Event("open"));
opened; // → 1{ once: true }: the handler removes itself after the first timeconst button = new EventTarget();
let count = 0;
const onClick = () => count++;
button.addEventListener("click", onClick);
button.addEventListener("click", onClick);
button.addEventListener("click", () => count++);
button.dispatchEvent(new Event("click"));
count; // → 2 — the repeated onClick is ignored, the new arrow is a different functionResults after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
Every element keeps a list of listeners: "event type → function" pairs. addEventListener adds a pair to that list. When the event happens, the browser creates an event object and calls the functions from the list one by one, passing it as the first argument. It calls them later, separately from your code: a handler is a callback, just like the one in setTimeout.
A few details:
- the same function for the same type is added only once; the repeat is ignored;
removeEventListenerlooks for the very same function (compared by reference), so you can't remove an anonymous arrow: keep the function in a variable;- the
{ once: true }option removes the handler by itself after the first call; - a third argument of
trueor{ capture: true }subscribes to the capture phase instead of bubbling.
The old way, button.onclick = fn, still works, but the property holds just one function: assigning a second one wipes out the first. addEventListener lets you keep any number of independent handlers, which is why libraries and analytics use it.
Traps
How it differs from…
setTimeout()andclearTimeout()Both take a callback that gets called later. setTimeout calls it once, after a delay;
addEventListenercalls it every time the event happens, until the handler is removed.
When to pick something else
When there are many similar elements (a product list, table rows) or they come and go, don't attach a handler to each: attach one to the shared container (delegation). And if you need to catch an event exactly once, don't remove the handler by hand: there's { once: true }.