JavaScript Events: addEventListener, the Event Object, Bubbling, Capturing and Delegation
Handle browser events properly: event types and categories, addEventListener options (once, passive, capture, signal), removing listeners, the event object, this and currentTarget, capture, target and bubble phases, delegation, preventDefault, stopPropagation, and custom events with CustomEvent.
kvi5hnuCode Sprout team member8 min readOn this page
Browser programs are event-driven (article 107): after the page loads, your code runs because something happened, such as a click, a key press, a form submission, a network response or a timer. This article covers how to listen for events, what information they carry, how they travel through the document, and how to create your own.
Three terms describe every event:
- Event type: a string naming what happened, like
"click","keydown","input"or"load". - Event target: the object it happened to, such as a button, the
document, thewindow, or aWorker. - Event listener (or handler): your function, which the browser calls when an event of that type reaches that target. When that happens, the event is said to be fired or dispatched.
Kinds of events
There are hundreds of event types, but they fall into a few groups:
| Category | Examples |
|---|---|
| Device-specific input | mousedown, mousemove, keydown, keyup, touchstart |
| Device-independent input | click (mouse, keyboard or tap), input (typing, pasting, voice), pointerdown/pointermove/pointerup (mouse, touch and pen) |
| User interface | focus, blur, change, submit, scroll |
| State changes | DOMContentLoaded, load, online/offline, popstate, visibilitychange |
| API-specific | media events like play and volumechange, message from workers, open/message on WebSockets |
Prefer the device-independent events. click also fires when a focused button is activated with Enter or Space, so it's accessible. Pointer events handle mouse, touch and stylus with one set of listeners, and input catches every way text can change, which keydown misses.
Registering listeners
target.addEventListener(type, listener, options?) is the standard way:
const button = document.querySelector("#save");
function save(event) {
console.log("saving after", event.type);
}
button.addEventListener("click", save);
button.removeEventListener("click", save); // needs the same function reference
Any number of listeners can be registered for the same event; they run in registration order. Registering the same function twice for the same type is ignored. To remove a listener, you must pass the same function object, which is why anonymous arrow functions can't be removed that way.
The older alternative is an event handler property: button.onclick = save. It allows only one handler per event type (assigning again replaces it), so prefer addEventListener. HTML attributes like <button onclick="save()"> are worse still (article 107).
Listener options
element.addEventListener("click", handler, {
once: true, // remove automatically after the first call
passive: true, // promise never to call preventDefault()
capture: false, // run in the capture phase instead of bubbling (see below)
signal: controller.signal, // remove when the AbortController is aborted
});
oncesuits one-time actions like an intro animation or a confirmation.passive: truelets the browser start scrolling immediately fortouchmoveandwheellisteners, instead of waiting to see whether you cancel the scroll. Browsers already treat these listeners as passive by default onwindow,documentandbody.signalis the modern way to clean up: oneabort()removes every listener registered with that signal. That's ideal for components that attach many listeners and must detach them all when they're destroyed.
EventTarget is part of Node too, so these mechanics can be tried outside the browser:
const target = new EventTarget();
const log = (event) => console.log("log:", event.type);
target.addEventListener("ping", log);
target.addEventListener("ping", log); // duplicate: ignored
target.addEventListener("ping", () => console.log("once only"), { once: true });
const controller = new AbortController();
target.addEventListener("ping", () => console.log("until aborted"), { signal: controller.signal });
target.dispatchEvent(new Event("ping"));
controller.abort();
target.dispatchEvent(new Event("ping"));
log: ping
once only
until aborted
log: ping
The event object
A listener receives one argument, an event object describing what happened. Every event has:
| Property | Meaning |
|---|---|
type | the event type string |
target | the object where the event originated (for example, the exact element clicked) |
currentTarget | the object whose listener is running right now |
timeStamp | when the event happened, in milliseconds since page load |
isTrusted | true if the browser generated it from real user action, false if a script dispatched it |
defaultPrevented | whether preventDefault() was called |
Specific event types add more:
- Mouse and pointer events have
clientX/clientY(viewport coordinates),button,pointerType, and the modifier flagsshiftKey,ctrlKey,altKeyandmetaKey. - Keyboard events have
key(the character or name produced, like"a","Enter"or"ArrowLeft"),code(the physical key, like"KeyA") andrepeat. - Input events carry
inputTypeanddata, and the new value is inevent.target.value.
document.addEventListener("keydown", (event) => {
if ((event.ctrlKey || event.metaKey) && event.key === "s") {
event.preventDefault(); // stop the browser's "Save page" dialog
saveDocument();
}
});
this inside listeners
In a listener defined with function, this is the currentTarget. Arrow functions don't have their own this, so use event.currentTarget instead. That's clearer in any case. You can also pass an object with a handleEvent(event) method as the listener, and it's called with this set to that object.
The return value of a listener added with addEventListener is ignored. (In handler properties, returning false cancels the default action, a legacy convention.)
Listeners run synchronously during dispatch. A dispatchEvent call returns only after every listener has run, and an exception in one listener is reported (as an uncaught error) without stopping the others.
How events travel: capture, target, bubble
For an event on an element inside the document, the browser doesn't only notify that element. The event propagates along the path from the window down to the target and back up:

- Capture phase: from
windowdown to the target's parent, running listeners registered with{ capture: true }. - Target phase: listeners on the target element itself.
- Bubble phase: back up from the parent to
window, running ordinary listeners.
Most events bubble. Some don't, including focus, blur, load (on elements), mouseenter and mouseleave. Bubbling alternatives exist for most of them, such as focusin and focusout.
<ul id="menu">
<li><button data-action="open">Open</button></li>
</ul>
<script type="module">
const menu = document.querySelector("#menu");
menu.addEventListener("click", (e) => console.log("bubble:", e.currentTarget.id, "target:", e.target.tagName));
menu.addEventListener("click", () => console.log("capture runs first"), { capture: true });
// clicking the button logs: "capture runs first", then "bubble: menu target: BUTTON"
</script>
Capturing listeners let an ancestor see an event before its target does, which is useful for debugging, closing a dropdown when the user clicks elsewhere, or blocking interaction during a drag.
Event delegation
Because events bubble, one listener on a container can handle events for all its descendants, including elements added later. This is event delegation:
const list = document.querySelector("#todo-list");
list.addEventListener("click", (event) => {
const button = event.target.closest("button[data-action]"); // what was really clicked?
if (!button || !list.contains(button)) return;
const item = button.closest("li");
if (button.dataset.action === "delete") item.remove();
if (button.dataset.action === "done") item.classList.toggle("done");
});
event.targetmay be a nested element (an icon inside the button), soclosest(selector)(article 109) walks up to the element you care about.- One listener replaces hundreds, uses less memory, and keeps working for items added later.
- Frameworks such as React use delegation internally, attaching their listeners at the root.
Cancelling: preventDefault and stopPropagation
Default actions. Many events trigger browser behavior: following a link, submitting a form, checking a checkbox, scrolling, opening the context menu. event.preventDefault() cancels that behavior. It doesn't stop other listeners from running.
form.addEventListener("submit", async (event) => {
event.preventDefault(); // don't reload the page
await fetch("/api/signup", { method: "POST", body: new FormData(form) });
});
preventDefault() has no effect in a passive listener, or on events that aren't cancelable.
Propagation. event.stopPropagation() stops the event from reaching any further nodes on its path, but other listeners on the current node still run. event.stopImmediatePropagation() also skips the remaining listeners on the current node. Use these sparingly: other code, such as analytics, a dropdown that closes on outside clicks, or a framework, may rely on seeing the event bubble. Checking event.target in a delegated handler is usually a better design.
Custom events
Any EventTarget can dispatch events, including your own types, which makes events a convenient way for parts of a program to communicate without knowing about each other. CustomEvent carries data in its detail property:
class Cart extends EventTarget {
#items = [];
add(item) {
this.#items.push(item);
this.dispatchEvent(new CustomEvent("change", { detail: { count: this.#items.length, item } }));
}
}
const cart = new Cart();
cart.addEventListener("change", (e) => console.log(`badge shows ${e.detail.count} (${e.detail.item})`));
cart.addEventListener("change", (e) => console.log("saving", e.detail.item));
cart.add("tea");
badge shows 1 (tea)
saving tea
dispatchEvent returns false if the event was cancelable and a listener called preventDefault(), so the dispatcher can ask "may I do this?":
const editor = new EventTarget();
editor.addEventListener("before-close", (event) => {
if (event.detail.unsaved) event.preventDefault();
});
const allowed1 = editor.dispatchEvent(new CustomEvent("before-close", { cancelable: true, detail: { unsaved: true } }));
const allowed2 = editor.dispatchEvent(new CustomEvent("before-close", { cancelable: true, detail: { unsaved: false } }));
console.log(allowed1, allowed2);
false true
On DOM elements, pass bubbles: true (and composed: true to cross shadow DOM boundaries, article 113) so ancestors can listen: el.dispatchEvent(new CustomEvent("item-selected", { bubbles: true, detail })). Events created by scripts have isTrusted === false, and the browser won't perform trusted default actions for them, such as opening a file picker.
Common questions
What's the difference between event.target and event.currentTarget?
target is where the event started (the innermost element clicked). currentTarget is the element whose listener is running, which differs from target during capture and bubbling.
Why doesn't removeEventListener remove my listener?
You must pass the exact same function (and the same capture value). An inline arrow function creates a new function each time. Keep a reference, or register with an AbortController signal and call abort().
preventDefault or stopPropagation?
They do different things. preventDefault cancels the browser's built-in action (navigation, form submission, scrolling). stopPropagation stops the event from reaching ancestor listeners. Most code needs the first and rarely the second.
Should I use click or pointerdown/touchstart for buttons?
click. It fires for mouse, touch, pen and keyboard activation, so it's accessible and consistent. Use pointer events for drawing, dragging and gestures.
Summary
- Listen with
addEventListener(type, fn, options);once,passive,captureandsignalcontrol behavior and cleanup. - The event object describes what happened:
type,target,currentTarget, plus type-specific data likekeyorclientX. - Events travel in three phases: capture (down), target, bubble (up); most events bubble.
- Delegation handles many elements with one listener on a container, using
event.target.closest(). preventDefault()cancels default browser actions;stopPropagation()stops propagation and is rarely needed.CustomEventwithdetaillets anyEventTarget, including your own classes, announce things; cancelable events let listeners veto actions.
Practice Questions
A list has 1,000 <li> items, and more are added over time. How do you handle clicks on any item efficiently?
Answer
Use event delegation: add one click listener to the <ul> and find the item with event.target.closest("li"). It works for items added later and avoids 1,000 separate listeners.
Why can't this listener be removed, and how do you fix it?
button.addEventListener("click", () => track("buy"));
button.removeEventListener("click", () => track("buy"));
Answer
Each arrow expression creates a new function, so removeEventListener receives a different function from the one that was added. Keep a reference to the function:
const onBuy = () => track("buy");
button.addEventListener("click", onBuy);
button.removeEventListener("click", onBuy);
Or register with { signal: controller.signal } and call controller.abort().
What's logged when the button is clicked?
outer.addEventListener("click", () => console.log("outer bubble"));
outer.addEventListener("click", () => console.log("outer capture"), { capture: true });
button.addEventListener("click", () => console.log("button"));
Answer
outer capture, then button, then outer bubble. Here button is inside outer, so the capture phase runs first going down, then the target's listener, then bubbling going up.
How does code that dispatches a cancelable custom event find out whether a listener vetoed it?
Answer
dispatchEvent returns false if any listener called preventDefault() on a cancelable event. You can also check event.defaultPrevented after dispatching.
Previous: JavaScript in the Browser: Scripts, Modules, defer, async and the Page Lifecycle
Next: Selecting and Traversing the DOM: querySelector, closest, matches and Node Relationships

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.