Why does one click trigger several handlers?
<div id="phase-panel">
<button id="save-button" type="button">Save</button>
</div>function mountPhaseDemo(root) {
const panel = root.querySelector("#phase-panel");
const saveButton = root.querySelector("#save-button");
if (
!(panel instanceof HTMLElement) ||
!(saveButton instanceof HTMLButtonElement) ||
!panel.contains(saveButton)
) {
throw new Error("Invalid event phase demo markup.");
}
const controller = new AbortController();
const options = { signal: controller.signal };
function logPhase(label) {
return (event) => {
console.log(label, event.eventPhase);
};
}
panel.addEventListener("click", logPhase("panel capture"), {
...options,
capture: true,
});
saveButton.addEventListener("click", logPhase("button capture"), {
...options,
capture: true,
});
saveButton.addEventListener("click", logPhase("button bubble"), options);
panel.addEventListener("click", logPhase("panel bubble"), options);
return () => controller.abort();
}
export const disposePhaseDemo = mountPhaseDemo(document);
// Click Save:
// panel capture 1
// button capture 2
// button bubble 2
// panel bubble 3
The browser builds an event path through the target's ancestors. Capture listeners run toward the target, then the target is handled, and events with bubbles: true travel back through the ancestors. addEventListener does not enable capture by default. [1][2]
Clicking Save produces the four console messages in the order shown. At the button, both the capture and regular listener report eventPhase 2. The capture option is therefore not the same as the phase value at the target. Listeners on the same object with the same capture setting are invoked in registration order. [1]
Each example is independent. Insert the HTML into a document, put CSS (if present) in a separate stylesheet, and load JavaScript from a file using <script type="module" src="app.js"></script>. The mount function checks the required DOM structure and returns a cleanup function. Call it before unmounting the view. Missing controls are integration errors, not failures to silently ignore.
Why is target a span instead of the button?
<button id="save" type="button">
<span>Save</span>
</button>function mountTargetDemo(root) {
const saveButton = root.querySelector("#save");
if (!(saveButton instanceof HTMLButtonElement)) {
throw new Error("Save button is missing.");
}
const controller = new AbortController();
const pendingTimers = new Set();
function handleClick(event) {
const clickedElement = event.target;
const button = event.currentTarget;
if (
!(clickedElement instanceof Element) ||
!(button instanceof HTMLButtonElement)
) {
return;
}
console.log(clickedElement.tagName, button.tagName);
// Run after event dispatch, in a later task.
const timerId = setTimeout(() => {
pendingTimers.delete(timerId);
console.log(event.currentTarget); // null
console.log(button.id); // "save"
}, 0);
pendingTimers.add(timerId);
}
saveButton.addEventListener("click", handleClick, {
signal: controller.signal,
});
return () => {
controller.abort();
for (const timerId of pendingTimers) {
clearTimeout(timerId);
}
pendingTimers.clear();
};
}
export const disposeTargetDemo = mountTargetDemo(document);
event.target is the target exposed to the current listener; in ordinary DOM it is often the deepest clicked element. event.currentTarget is the object whose listener is currently executing. Clicking the Save label logs SPAN BUTTON, whereas clicking the button itself can log BUTTON BUTTON. [1][3]
After event dispatch finishes, currentTarget is null. Capture the control reference inside the listener. The example uses setTimeout to read the value in a later task, after dispatch has finished. Cleanup cancels pending timers. A microtask alone does not guarantee that the entire dispatch has finished. For a real asynchronous request, handle rejection and cancellation as well. [1][3]
How do I cancel navigation without blocking other listeners?
<section id="navigation-demo" aria-labelledby="navigation-heading">
<h2 id="navigation-heading">Navigation experiment</h2>
<label>
<input id="cancel-navigation" type="checkbox" />
Cancel fragment navigation (demo)
</label>
<p>
<a id="details-link" href="#details-section">Details</a>
</p>
</section>
<section id="details-section" aria-labelledby="details-heading">
<h2 id="details-heading">Product details</h2>
</section>function mountNavigationDemo(root) {
const panel = root.querySelector("#navigation-demo");
const detailsLink = root.querySelector("#details-link");
const cancelNavigation = root.querySelector("#cancel-navigation");
if (
!(panel instanceof HTMLElement) ||
!(detailsLink instanceof HTMLAnchorElement) ||
!(cancelNavigation instanceof HTMLInputElement) ||
cancelNavigation.type !== "checkbox" ||
!panel.contains(detailsLink) ||
!panel.contains(cancelNavigation)
) {
throw new Error("Invalid navigation demo markup.");
}
const controller = new AbortController();
const options = { signal: controller.signal };
function handleLinkClick(event) {
if (!(event instanceof MouseEvent)) {
return;
}
const isModifiedClick =
event.button !== 0 ||
event.altKey ||
event.ctrlKey ||
event.metaKey ||
event.shiftKey;
if (cancelNavigation.checked && event.cancelable && !isModifiedClick) {
event.preventDefault();
}
console.log("Default action canceled:", event.defaultPrevented);
}
function handlePanelClick(event) {
if (event.target instanceof Node && detailsLink.contains(event.target)) {
console.log("Panel still receives the click");
}
}
detailsLink.addEventListener("click", handleLinkClick, options);
panel.addEventListener("click", handlePanelClick, options);
return () => controller.abort();
}
export const disposeNavigationDemo = mountNavigationDemo(document);
preventDefault() cancels the default action of a cancelable event in a non-passive listener. Check the demo checkbox to cancel ordinary fragment navigation while the parent handler still runs. When unchecked, the link works natively; modified clicks are not intercepted. stopPropagation() stops further propagation but does not cancel navigation by itself. [4][5]
stopImmediatePropagation() additionally prevents remaining listeners on the current object from running. In a card with several actions, recognizing which control was activated is usually better than suppressing every event. A native button and a separate details link are preferable to nesting interactive controls inside a clickable link. [1]
How do I handle dynamically added buttons?
<form id="task-form">
<label for="task-name">Task name</label>
<input id="task-name" name="taskName" required maxlength="100" />
<button type="submit">Add task</button>
</form>
<ul id="tasks" data-task-list>
<li>
<button
class="task-toggle"
type="button"
data-action="toggle"
aria-pressed="false"
>
<span>Task 1</span>
</button>
</li>
</ul>.task-toggle[aria-pressed="true"] {
font-weight: 700;
text-decoration: line-through;
}
.task-toggle:focus-visible {
outline: 2px solid currentColor;
outline-offset: 2px;
}function mountTaskList(root) {
const taskList = root.querySelector("#tasks");
const taskForm = root.querySelector("#task-form");
const taskName = root.querySelector("#task-name");
if (
!(taskList instanceof HTMLUListElement) ||
!(taskForm instanceof HTMLFormElement) ||
!(taskName instanceof HTMLInputElement) ||
taskName.form !== taskForm ||
taskName.maxLength <= 0
) {
throw new Error("Invalid task list markup.");
}
const controller = new AbortController();
const options = { signal: controller.signal };
function handleTaskClick(event) {
if (!(event.target instanceof Element)) {
return;
}
const button = event.target.closest('button[data-action="toggle"]');
if (
!(button instanceof HTMLButtonElement) ||
!taskList.contains(button) ||
button.closest("[data-task-list]") !== taskList ||
button.matches(":disabled")
) {
return;
}
const pressed = button.getAttribute("aria-pressed") === "true";
button.setAttribute("aria-pressed", String(!pressed));
}
function addTask(event) {
event.preventDefault();
const name = taskName.value.trim();
if (!name || name.length > taskName.maxLength) {
taskName.setCustomValidity("Enter a valid task name.");
taskName.reportValidity();
return;
}
const item = document.createElement("li");
const button = document.createElement("button");
const label = document.createElement("span");
button.type = "button";
button.className = "task-toggle";
button.dataset.action = "toggle";
button.setAttribute("aria-pressed", "false");
label.textContent = name;
button.append(label);
item.append(button);
taskList.append(item);
taskForm.reset();
taskName.focus();
}
function clearValidation() {
taskName.setCustomValidity("");
}
taskList.addEventListener("click", handleTaskClick, options);
taskForm.addEventListener("submit", addTask, options);
taskForm.addEventListener("reset", clearValidation, options);
taskName.addEventListener("input", clearValidation, options);
return () => {
controller.abort();
clearValidation();
};
}
export const disposeTaskList = mountTaskList(document);
Delegation registers a listener on a stable ancestor. closest() identifies the intended button even if its text or icon was clicked. Checking the nearest [data-task-list] prevents handling actions that belong to another nested list. [2][6]
The example toggles aria-pressed on existing and newly added buttons. Native buttons also support keyboard activation. The new task's label is assigned through textContent instead of HTML interpolation. Delegation reduces listener registrations, but each event still requires selector matching; it does not automatically guarantee faster execution.
Enter a task name and submit the form. Whitespace-only names are rejected, and the length limit comes from HTML. After adding a task, focus returns to the input. A separate stylesheet makes the pressed state visible without changing the button label. :disabled also accounts for a disabled ancestor fieldset.
Why do focus and mouseenter behave differently from click?
<form id="profile-form">
<label for="profile-name">Name</label>
<input id="profile-name" name="name" autocomplete="name" required />
<label for="profile-email">Email</label>
<input
id="profile-email"
name="email"
type="email"
autocomplete="email"
required
/>
</form>function mountFocusDemo(root) {
const profileForm = root.querySelector("#profile-form");
if (!(profileForm instanceof HTMLFormElement)) {
throw new Error("Profile form is missing.");
}
const controller = new AbortController();
function handleFocus(event) {
if (
!(event.target instanceof HTMLInputElement) ||
event.target.form !== profileForm
) {
return;
}
console.log("Focused:", event.target.name);
}
profileForm.addEventListener("focus", handleFocus, {
capture: true,
signal: controller.signal,
});
return () => controller.abort();
}
export const disposeFocusDemo = mountFocusDemo(document);
Not every event bubbles. focus and blur can be observed on ancestors using capture: true; the bubbling alternatives are focusin and focusout. Focusing the Name input logs its name without a dedicated listener per field. mouseenter also does not bubble; using mouseover requires distinguishing movement between descendants, for example with relatedTarget. [7][12]
The passive: true option declares that the listener will not cancel default actions. This matters for touch and wheel events, where cancellation may delay scrolling. If preventDefault() is necessary, check cancelable and the passive setting. Do not mechanically mark every listener as passive. [4][8]
How do I delegate events from Web Components?
<section id="catalog" aria-labelledby="catalog-heading">
<h2 id="catalog-heading">Catalog</h2>
<product-card product-id="p-42"></product-card>
</section>const PRODUCT_SELECT_EVENT = "product-select";
class ProductCard extends HTMLElement {
#button;
#controller;
constructor() {
super();
const root = this.attachShadow({ mode: "open" });
this.#button = document.createElement("button");
this.#button.type = "button";
this.#button.textContent = "Select product";
root.append(this.#button);
}
connectedCallback() {
this.#controller?.abort();
this.#controller = new AbortController();
this.#button.addEventListener("click", this.#handleSelect, {
signal: this.#controller.signal,
});
}
disconnectedCallback() {
this.#controller?.abort();
this.#controller = undefined;
}
#handleSelect = () => {
const productId = this.getAttribute("product-id")?.trim();
if (!productId) {
return;
}
this.#button.dispatchEvent(
new CustomEvent(PRODUCT_SELECT_EVENT, {
bubbles: true,
composed: true,
detail: { productId },
}),
);
};
}
function mountCatalog(root) {
const catalog = root.querySelector("#catalog");
if (!(catalog instanceof HTMLElement)) {
throw new Error("Catalog is missing.");
}
const controller = new AbortController();
function handleProductSelect(event) {
if (
!(event instanceof CustomEvent) ||
!(event.target instanceof ProductCard) ||
!catalog.contains(event.target)
) {
return;
}
const productId = event.detail?.productId;
if (
typeof productId !== "string" ||
!productId.trim() ||
productId !== event.target.getAttribute("product-id")?.trim()
) {
return;
}
console.log(event.target.tagName, productId); // PRODUCT-CARD p-42
}
catalog.addEventListener(PRODUCT_SELECT_EVENT, handleProductSelect, {
signal: controller.signal,
});
return () => controller.abort();
}
customElements.define("product-card", ProductCard);
export const disposeCatalog = mountCatalog(document);
Shadow DOM changes the target visible to outside code. An event originating on an internal button may expose the component host as target to an external listener. composedPath() reveals the accessible path but does not expose internal nodes of a closed shadow root to outside code. [1][9]
Instead of depending on internal markup, the example emits a public product-select event with a product identifier in detail. bubbles: true allows propagation to ancestors and composed: true permits crossing the shadow boundary. The parent receives PRODUCT-CARD and p-42. A custom event is not proof of authorization; validate data at trust boundaries. [9][10]
The identifier comes from the product-id attribute; the receiver checks the event type, host and detail payload. The internal listener is registered in connectedCallback() and removed in disconnectedCallback(), so reconnecting the component does not multiply calls. Load the element definition only once. [13]
How do I clean up listeners and debug duplicate calls?
<section id="toolbar" aria-labelledby="toolbar-heading">
<h2 id="toolbar-heading">View actions</h2>
<button id="refresh-button" type="button">Refresh</button>
</section>const activeMounts = new WeakMap();
function mountToolbar(toolbar, { onRefresh, onViewportResize }) {
if (!(toolbar instanceof HTMLElement)) {
throw new Error("Toolbar is missing.");
}
const refreshButton = toolbar.querySelector("#refresh-button");
if (
!(refreshButton instanceof HTMLButtonElement) ||
typeof onRefresh !== "function" ||
typeof onViewportResize !== "function"
) {
throw new Error("Invalid toolbar configuration.");
}
activeMounts.get(toolbar)?.();
const controller = new AbortController();
const options = { signal: controller.signal };
function handleRefresh() {
onRefresh();
}
function handleResize() {
onViewportResize(window.innerWidth);
}
function dispose() {
controller.abort();
if (activeMounts.get(toolbar) === dispose) {
activeMounts.delete(toolbar);
}
}
refreshButton.addEventListener("click", handleRefresh, options);
window.addEventListener("resize", handleResize, options);
activeMounts.set(toolbar, dispose);
return dispose;
}
export const disposeToolbar = mountToolbar(
document.querySelector("#toolbar"),
{
onRefresh: () => console.log("Refresh requested"),
onViewportResize: (width) => console.log("Viewport width:", width),
},
);
// Call disposeToolbar() when the view is unmounted.
Repeatedly mounting a view with fresh anonymous functions can produce multiple reactions to one event. Removing a listener with removeEventListener requires the same event type, function reference and capture setting. Here one AbortController ties two listeners to the view lifecycle. After disposeToolbar() both stop responding. A subsequent mount creates a fresh controller. [1][8]
If the cause is still unclear, open Sources in Chrome DevTools and enable Event Listener Breakpoints for the relevant event. When execution pauses, inspect target, currentTarget, eventPhase, defaultPrevented, composedPath() and the call stack. Compare the number of invocations before mounting, after mounting and after cleanup. [11]
The refresh button and viewport resize use separate callbacks. A WeakMap disposes the previous mount of the same toolbar before registering new listeners. An old disposer cannot remove a newer registration. Mount the other examples once per lifecycle.
