Events
An event is a notification from the browser or from your own EventTarget: a click, a key, a load, a message. You handle it by registering a listener that receives an Event object.
Detailed Explanation
The page is not a loop you poll. The browser queues events and your listeners run as tasks (usually). element.addEventListener("click", handler) registers. removeEventListener("click", handler) removes the same function reference. An options object can set once, capture, passive, and signal (an AbortSignal that removes the listener when aborted).
The handler receives an event. event.target is the node that originated the event. event.currentTarget is the node whose listener is running. event.type is the name. preventDefault() cancels the browser's built-in action (a submit, a link) if the event is cancelable. stopPropagation() stops the event from reaching other nodes. stopImmediatePropagation() also stops other listeners on the same node.
Many events bubble: they travel from the target up to document. Some do not (focus uses a different path; focusin bubbles). Capture is the trip down. See event bubbling and capturing.
onclick = fn is a single property; a second assignment overwrites. addEventListener stacks. Prefer the latter. Inline onclick="..." in HTML is harder to test and mixes layers.
Custom events: element.dispatchEvent(new CustomEvent("cart:add", { detail: item, bubbles: true })). Same dispatch path as native events.
What it costs you: leaks (listeners on window that close over a view) and lost this (passing a method without bind). Passive listeners on touchstart/wheel tell the browser it can scroll without waiting for preventDefault; a non-passive listener can delay scroll.
Reach for events for user input and host notifications. Reach for polling only when no event exists. Reach for delegation when many children share a handler.
Code Examples
const button = document.querySelector("#save");
const ac = new AbortController();
function onSave(event) {
event.preventDefault();
console.log(event.currentTarget.id);
}
button.addEventListener("click", onSave, { signal: ac.signal });
// later
ac.abort();form.addEventListener("submit", (event) => {
event.preventDefault();
const data = new FormData(event.currentTarget);
console.log(data.get("email"));
});window.addEventListener(
"scroll",
() => {
/* update a progress bar */
},
{ passive: true },
);Common Gotchas
`removeEventListener` needs the same function and same capture flag
an inline arrow cannot be removed.
`preventDefault` on a passive listener is ignored
the browser already committed to scroll.
Method listeners lose `this`
use an arrow, `bind`, or `event.currentTarget`.
`onclick` assignment is not additive
a second write replaces the first handler.