Events: addEventListener, bubbling and delegation
A page is passive until something happens: a click, a key, a submit, a change of an input. The DOM reports each of them as an event that travels from the element where it happened up to the document, and a listener is a function registered for one type of event on one element. The same listener sees the event object, which carries what happened, where it happened and how to stop it.
There is no user in front of a program that runs in Node.js, so every program in this lesson raises its own events with dispatchEvent and passes the options a browser would pass, such as bubbles. That is also how a test drives a page: the listener code is the code under test, and the event is the input. The pages come from jsdom, set up as the first lesson of this part showed.
A listener on an element
addEventListener(type, listener) registers a function for one event type, and a second call with the same function does nothing, because a listener is registered once per type and function. removeEventListener needs that same reference: a function written out again is a different function and removes nothing. In the handler, target is where the event happened and currentTarget is the element the listener sits on.
The program clicks a button twice, removes the handler, clicks once more, and submits a form whose handler cancels the default.
The file listener.js:
const { JSDOM } = require('jsdom');
const html = '<!doctype html><body><button id="add">add</button></body>';
const dom = new JSDOM(html, { url: 'http://localhost/' });
const { window } = dom;
const { document } = window;
const button = document.querySelector('#add');
let seen = null;
button.addEventListener('click', (event) => {
seen = {
type: event.type,
target: event.target.id,
current: event.currentTarget.id,
button: event.button,
};
});
button.dispatchEvent(new window.MouseEvent('click'));
console.log('the listener ran:', seen !== null);
console.log('the type:', seen.type);
console.log('the target and the current target:', seen.target, seen.current);
console.log('the button number:', seen.button);
let count = 0;
const counter = () => {
count += 1;
};
button.addEventListener('click', counter);
button.dispatchEvent(new window.MouseEvent('click'));
button.dispatchEvent(new window.MouseEvent('click'));
console.log('two clicks:', count);
button.removeEventListener('click', counter);
button.dispatchEvent(new window.MouseEvent('click'));
console.log('after the removal:', count);
const form = document.createElement('form');
document.body.append(form);
form.addEventListener('submit', (event) => {
event.preventDefault();
});
const submit = new window.Event('submit', { cancelable: true });
form.dispatchEvent(submit);
console.log('the submit was cancelled:', submit.defaultPrevented, 'cancelable:', submit.cancelable);
node listener.js
the listener ran: true
the type: click
the target and the current target: add add
the button number: 0
two clicks: 2
after the removal: 2
the submit was cancelled: true cancelable: true
The count did not move after the removal, because the call passed the same function that had been registered. The submit handler cancelled the default action of the event, which is how a form keeps its data on the page instead of sending the reader to another address; the flag is readable on the event after the dispatch has finished.
Bubbling and capture
An event that happens on a button also passes through its parent, its grandparent and the document. The first phase is capture, from the document down to the target; then the target itself; then the bubble phase back up. A listener runs in the bubble phase by default, and the third argument of addEventListener with capture: true puts it in the capture phase. The bubbles option of the event decides whether it climbs at all, and a click has it by default in a browser while an event a program makes has to ask for it.
The program puts one listener on each level of a list and prints the order in which they ran, once without bubbling and once with it, and then adds a capture listener.
The file bubble.js:
const { JSDOM } = require('jsdom');
const html = '<!doctype html><body><ul id="list"><li><button>one</button></li></ul></body>';
const dom = new JSDOM(html, { url: 'http://localhost/' });
const { window } = dom;
const { document } = window;
const list = document.querySelector('#list');
const item = list.querySelector('li');
const button = item.querySelector('button');
const order = [];
function record(name) {
return () => {
order.push(name);
};
}
document.addEventListener('click', record('document'));
document.body.addEventListener('click', record('body'));
list.addEventListener('click', record('list'));
item.addEventListener('click', record('item'));
button.addEventListener('click', record('button'));
button.dispatchEvent(new window.MouseEvent('click'));
console.log('without bubbles:', order.join(' > '));
order.length = 0;
button.dispatchEvent(new window.MouseEvent('click', { bubbles: true }));
console.log('with bubbles:', order.join(' > '));
order.length = 0;
list.addEventListener('click', record('list capture'), true);
button.dispatchEvent(new window.MouseEvent('click', { bubbles: true }));
console.log('with a capture listener:', order.join(' > '));
node bubble.js
without bubbles: button
with bubbles: button > item > list > body > document
with a capture listener: list capture > button > item > list > body > document
Without the option the event never left the button, and with it the five listeners ran in the order of the tree, from the target upwards. The capture listener on the list ran first of all, before the target, because the capture phase reaches the list on the way down. That order is why a capture listener is the tool for intercepting a click before the element itself sees it.
Stopping the climb
stopPropagation stops the event from reaching the next element in the path, while the other listeners on the same element still run stopImmediatePropagation also skips those. A handler uses it when it fully owns the event, such as a button inside a row that must not open the row. It is a strong tool: a listener above never learns about the click, which is sometimes exactly the point and sometimes a bug that is hard to find.
The program has a click on the button stop at the button when the alt key is down, and prints both orders, then shows what immediate propagation does to a second listener on the same element.
The file stopprop.js:
const { JSDOM } = require('jsdom');
const html = '<!doctype html><body><ul id="list"><li><button>one</button></li></ul></body>';
const dom = new JSDOM(html, { url: 'http://localhost/' });
const { window } = dom;
const { document } = window;
const list = document.querySelector('#list');
const button = list.querySelector('button');
const order = [];
list.addEventListener('click', () => {
order.push('list');
});
button.addEventListener('click', (event) => {
order.push('button');
if (event.altKey) {
event.stopPropagation();
}
});
button.dispatchEvent(new window.MouseEvent('click', { bubbles: true }));
console.log('a plain click:', order.join(' > '));
order.length = 0;
button.dispatchEvent(new window.MouseEvent('click', { bubbles: true, altKey: true }));
console.log('a click with alt:', order.join(' > '));
order.length = 0;
const inner = document.createElement('button');
inner.textContent = 'stop';
inner.addEventListener('click', (event) => {
event.stopImmediatePropagation();
order.push('first inner');
});
inner.addEventListener('click', () => {
order.push('second inner');
});
list.append(inner);
inner.dispatchEvent(new window.MouseEvent('click', { bubbles: true }));
console.log('stopImmediatePropagation:', order.join(' > '));
node stopprop.js
a plain click: button > list
a click with alt: button
stopImmediatePropagation: first inner
The plain click reached the list and the one with alt did not. The third line is the stronger method: the second listener on the same button never ran, and neither did the list. A handler that calls either method should say so in a comment, because the next reader will look for the listener that did not fire.
One listener for many elements
A list of a hundred buttons does not need a hundred listeners. One listener on the container sees every click through bubbling, and event.target.closest finds the button and the row it belongs to. This is delegation: it costs one function, it works for rows added later, and it keeps the handler beside the data it changes. The lesson on selecting elements built the two methods it uses.
The program clicks each button in a list of three rows and then clicks the empty part of the list, and counts how many times the one listener ran.
The file delegate.js:
const { JSDOM } = require('jsdom');
const html = [
'<!doctype html>',
'<body>',
'<ul id="list">',
'<li data-id="1"><button>remove</button></li>',
'<li data-id="2"><button>remove</button></li>',
'<li data-id="3"><button>remove</button></li>',
'</ul>',
'</body>',
].join('');
const dom = new JSDOM(html, { url: 'http://localhost/' });
const { window } = dom;
const { document } = window;
const list = document.querySelector('#list');
const removed = [];
let clicks = 0;
list.addEventListener('click', (event) => {
clicks += 1;
const button = event.target.closest('button');
if (button === null) {
return;
}
const item = button.closest('li');
removed.push(item.dataset.id);
});
for (const button of document.querySelectorAll('li button')) {
button.dispatchEvent(new window.MouseEvent('click', { bubbles: true }));
}
list.dispatchEvent(new window.MouseEvent('click', { bubbles: true }));
console.log('the ids that were removed:', removed.join(', '));
console.log('one listener saw every click:', clicks);
console.log('the list has the buttons still:', list.querySelectorAll('button').length);
node delegate.js
the ids that were removed: 1, 2, 3
one listener saw every click: 4
the list has the buttons still: 3
Four clicks reached one function, three of them from a button and one from the list itself, and the guard sent that last one away without an error. The page has no per-button listener at all, so a row that the program creates later is handled by the same code without a second registration.
Exercises
- Register the same function twice on one button and click it. How many times does it run, and why?
- Remove a listener with a function written out again in the second call. Does the listener go away, and what does that say about function identity?
- Dispatch a click on the item instead of the button with bubbling on. Which listeners run, and what is event.target in each of them?
- Add a fourth row to the list and click its button. Why does the delegated listener work without a change to the code?
- Make an event with new window.Event('save') and listen for it on the document. Does a custom type need any registration?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does addEventListener need at least?
Answer
A type and a function
The type says which events to listen for and the function is what runs for each of them.
-
What does this program print?
const { JSDOM } = require("jsdom"); const dom = new JSDOM("<button id=add>add</button>", { url: "http://localhost/" }); const button = dom.window.document.querySelector("#add"); let count = 0; button.addEventListener("click", () => { count += 1; }); button.dispatchEvent(new dom.window.MouseEvent("click")); button.dispatchEvent(new dom.window.MouseEvent("click")); console.log(count);Answer
2
Each dispatch runs the listener once, and the count is a variable of the program, not of the page.
-
In which order do the listeners of a bubbling click run?
Answer
From the target up to the document
The bubble phase starts at the target and climbs, while capture runs in the other direction first.
-
What does this program print?
const { JSDOM } = require("jsdom"); const dom = new JSDOM("<ul><li><button>one</button></li></ul>", { url: "http://localhost/" }); const list = dom.window.document.querySelector("ul"); const item = list.querySelector("li"); let seen = 0; list.addEventListener("click", () => { seen += 1; }); item.dispatchEvent(new dom.window.MouseEvent("click")); console.log(seen);Answer
0
The event was made without bubbles, so it never left the item and the list heard nothing.
-
What does stopPropagation do?
Answer
It keeps the event from reaching the next element in the path
The climb ends there; the listeners already on this element still run, and the default action is untouched.
-
What does this program print?
const { JSDOM } = require("jsdom"); const dom = new JSDOM("<ul id=list><li><button>remove</button></li></ul>", { url: "http://localhost/" }); const list = dom.window.document.querySelector("#list"); list.addEventListener("click", (event) => { const button = event.target.closest("button"); console.log(button === null ? "no button" : button.textContent); }); list.dispatchEvent(new dom.window.MouseEvent("click", { bubbles: true }));Answer
no button
The target is the list itself, and no button is on the path upwards from it, so closest answers null.
-
What does removeEventListener need?
Answer
The same function reference that was registered
Two functions with the same body are two objects, and only the registered one can be removed.
-
What does this program print?
const { JSDOM } = require("jsdom"); const dom = new JSDOM("<form id=note></form>", { url: "http://localhost/" }); const form = dom.window.document.querySelector("#note"); form.addEventListener("submit", (event) => { event.preventDefault(); }); console.log(form.dispatchEvent(new dom.window.Event("submit", { cancelable: true })));Answer
false
dispatchEvent answers false when a handler cancelled a cancelable event with preventDefault.
-
Which phase does a listener with capture: true run in?
Answer
The capture phase, from the document down to the target
The third argument moves the listener to the way down, which is why it runs before the target handler.
-
What does this program print?
const { JSDOM } = require("jsdom"); const dom = new JSDOM("<ul id=list><li><button>one</button></li></ul>", { url: "http://localhost/" }); const list = dom.window.document.querySelector("#list"); list.addEventListener("click", (event) => { console.log(event.target.tagName, event.currentTarget.tagName); }); list.querySelector("button").dispatchEvent(new dom.window.MouseEvent("click", { bubbles: true }));Answer
BUTTON UL
The target stays the button where the click happened, and the current target is where the listener sits.
The programs on this page were run with Node.js 24.22.1 against jsdom 30.1.3 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev