T4 JavaScript · Lesson 9
Events
Making a page answer people: listening for clicks, typing, keys and forms with addEventListener, reading the event object, stopping a form from leaving the page, how events bubble up the tree, one listener for many elements, and removing listeners.
- listen for an event with addEventListener, and pass the handler itself, not its answer
- read the event object: its type, its target and, for keys, its key
- answer typing and forms with the input, change and submit events, and keep a form on the page with preventDefault
- say how an event bubbles up the tree, and stop it when needed
- handle many elements, even ones added later, with one listener on their parent
- remove a listener, listen only once, and tell onclick from addEventListener
The back cover
A page that only runs from top to bottom cannot answer anyone. Events let it wait: for a click, a key, a letter typed or a form sent, and then run a function at that moment. That is how a button counts, a search box narrows a list, and a form checks its fields.
These pages show how to listen for an event and what the event object tells a handler. They show the events of forms, and how to keep a form from leaving the page. They show how an event bubbles up the tree, how one listener can serve many elements, and how to take listeners off again.
Before you start
The story: Bells that ring for nobody
The Harbour Office's panel now has brass buttons, one beside each ferry, marked Remind me. A passenger presses one, and nothing happens. Another presses it twice, then thumps it, and still nothing. Yet each morning, as the panel wakes, every reminder bell rings once, all together, with nobody near.
And when a new ferry is added to the panel in the afternoon, its button does not even click.
Master Hakim Verge listens to the bells' morning chorus with his eyes shut. "A machine that rings when nobody asks, and stays silent when they do," he says. "Somebody told it what to do, instead of telling it what to listen for."
The DOM lesson's scripts ran once, as the page loaded, and then stopped. A real page must also answer people while they use it: a press of a button, a word typed into a search box, a form sent, a key pressed. Each of these is an event, and a script can ask the browser to run a function whenever one happens. This lesson is about that asking.
It builds on these ideas. Each one has a tiny example, so you can check that you remember it.
| What you already know | A tiny example | Where it comes back |
|---|---|---|
| Finding elements. | document.querySelector("button") | You listen on an element you have found. |
| Changing elements. | out.textContent = "4.15" | Most handlers change the page. |
| Callbacks. | prices.find((p) => p > 100) | A handler is a callback the browser calls. |
| Passing a function, not its answer. | say(text, shout), not shout() | The commonest event bug. |
| The tree. | Parents and children. | Events travel up it. |
| Closures. | A counter that remembers. | Handlers often keep a count. |
| Objects and properties. | event.type | Every event arrives as an object. |
| Forms. | <form> with an input and a button. | Their events, and stopping a form from leaving. |
| The DOM's lists from data. | A render function. | Rows added later need listening too. |
| closest and matches. | Not met yet. | New here: finding the element an event came from. |
By the end of this lesson you will be able to:
- listen for an event with
addEventListener, and pass the handler itself, not its answer; - read the event object: its type, its target and, for keys, its key;
- answer typing and forms with the
input,changeandsubmitevents, and keep a form on the page withpreventDefault; - say how an event bubbles up the tree, and stop it when needed;
- handle many elements, even ones added later, with one listener on their parent;
- remove a listener, listen only once, and tell
onclickfrom addEventListener.
How to follow this lesson
The blocks are small pages. Press Run, then press the buttons and type into the boxes of the page under the code. The notes under each block say what the kit did in Chrome, such as pressing a button twice, and what the page showed after it.
In one line
An event is something that happens on a page, such as a click or a key; a script asks the browser to call a function each time it happens.
Listening for an event
At a glance
A doorbell does nothing until someone presses it, and then it rings, every time. Nobody rings it in advance. Wiring a bell means saying once, when this button is pressed, ring, and then leaving it to wait.
On a page, element.addEventListener("click", handler) is that wiring. The script only sets up the listener; the browser calls the handler later, at every click. Pass the function itself, with no brackets: with brackets, it runs at once, a single time, and the click does nothing.
Take a guess: If a long loop is running when someone clicks, when does the click's handler run?
A doorbell does nothing until someone presses it, and then it rings, every time, for as long as the house stands. Nobody rings it in advance. Wiring a bell means saying "when this button is pressed, ring", once, and then leaving it to wait.
Something that happens on a page, which the browser tells scripts about: a click, a key pressed, text typed, a form sent, the page finished loading. Each kind of event has a name, such as "click".
A method of every element: element.addEventListener("click", handler) asks the browser to call the function handler each time a click happens on element. The function is called a listener or handler.
<!DOCTYPE html>
<button id="b">Next ferry</button>
<p id="out">--.--</p>
<script>
const button = document.getElementById("b");
button.addEventListener("click", () => {
document.getElementById("out").textContent = "4.15";
});
</script>
Checked in Chrome
- before any press, the panel still shows its dashes
- after the kit pressed the button, it shows 4.15
The script ran once, as the page loaded, and did only one thing: it asked to be told about clicks. The arrow function did not run then. It ran later, when the button was pressed, and it will run again at every press. This is the shape of almost all the JavaScript on real pages: set up listeners, then wait.
A handler that remembers
A handler is an ordinary function, so it can use names around it, as the scope lesson's closures did. A count kept outside the handler lasts from one press to the next:
<!DOCTYPE html>
<button id="b">Remind me</button>
<p id="out">Pressed 0 times</p>
<script>
let presses = 0;
document.getElementById("b").addEventListener("click", () => {
presses++;
document.getElementById("out").textContent = `Pressed ${presses} times`;
});
</script>
Checked in Chrome
- after two presses, the page counts 2
Pass the function, not its answer
The bells of the story rang once at load and never again, because of a slip you met in the functions lesson: brackets on a callback. addEventListener("click", ring()) calls ring at once, while the page loads, and hands addEventListener whatever ring returned, which is undefined. The browser then has nothing to call at a press:
<!DOCTYPE html>
<button id="b">Remind me</button>
<p id="out">--</p>
<script>
let rings = 0;
function ring() {
rings++;
document.getElementById("out").textContent = `Rang ${rings} times`;
}
document.getElementById("b").addEventListener("click", ring());
</script>
Checked in Chrome
- the bell rang once as the page loaded, with nobody pressing
- and a press changes nothing
Remove the brackets, addEventListener("click", ring), and the function itself is handed over, to be called at each press. No error appears in the broken version: addEventListener quietly accepts undefined, which makes this bug hard to spot by reading the Console.
Worked example 1
A school's quiz page has a button Show answer under each question. Pressing it should show the answer, 7, in a paragraph that starts empty. Write the listener, and check it with one press.
What we have: a button and an empty paragraph
What we need: the answer shown only after a press
The plan: find the button, and give addEventListener an arrow that sets the paragraph's text
<!DOCTYPE html>
<p>3 + 4 = ?</p>
<button id="b">Show answer</button>
<p id="out"></p>
<script>
document.getElementById("b").addEventListener("click", () => {
document.getElementById("out").textContent = "7";
});
</script>
Checked in Chrome
- before the press, the answer is hidden
- after the press, it shows 7
The answer 7 appears only after the press.
Check: the first check, before any press, found the paragraph empty.
A path that fails: writing the answer straight into the paragraph in the script, without a listener. The answer then shows the moment the page loads, and the button does nothing.
When you are stuck: a handler never runs, or runs at load
If it runs at load and never again, look for brackets after the handler's name in addEventListener.
If it never runs, check that the element you listen on is the one being pressed: print it.
Check the event's name: "click", all small letters, with no "on" in front.
Put a console.log("handler ran"); as the first line of the handler.
Your turn
What is wrong with button.addEventListener("click", save());?Tap to reveal
- save() calls save at once, while the page loads.
- addEventListener receives save's answer, not the function, so nothing runs at a press.
The brackets: write button.addEventListener("click", save);.
When does the arrow in b.addEventListener("click", () => { ... }) run?Tap to reveal
- Not when the line runs; that line only asks to be told.
- Each time the button is clicked.
At every click of the button, and never before.
Why can a handler count presses with let presses = 0; made outside it?Tap to reveal
- The handler is a closure: it can see and change presses.
- presses is made once, outside, so it lasts between calls.
Because the count lives outside the handler, and the handler keeps it alive.
Did you know?
A promise not to stop scrolling
A listener can promise not to stop scrolling. The option passive: true says the handler will never call preventDefault, and MDN explains that the browser then does not need to wait for it before scrolling. The DOM standard now makes passive the default for touchstart, touchmove, wheel and mousewheel listeners on the window and the document. So a page that listens for touches everywhere still scrolls at once.
Why it fits here: It adds a third argument to this topic's addEventListener: an options object, which can tell the browser that scrolling need not wait.
Sources: MDN: EventTarget.addEventListener(); WHATWG: DOM Standard
A click waits its turn
A click never interrupts code that is already running. MDN calls JavaScript's rule run-to-completion: each job is processed completely before any other job is processed. A click during a long loop waits in a queue, and its handler runs only when the loop has ended. MDN names the cost too: while a job takes too long, the page cannot answer clicks or scrolling.
Why it fits here: It explains this topic's later: a handler never cuts into running code, but waits until the browser is free to call it.
Sources: MDN: JavaScript execution model; WHATWG: HTML Standard, event loops
In one line
element.addEventListener("click", handler) asks the browser to call handler at every click. The script only sets up the listener; the handler runs later. Pass the function itself, with no brackets, or it runs at once and never again.
The event object
At a glance
A doorbell only says that someone pressed it. A smart one also says which door, at what time, and whether the press was long. The browser does the same for a handler.
When it calls a handler, it passes one argument, an event object full of facts about what happened. It is usually named event, or e for short. The property event.type names the event, event.target is the element it happened on, and event.key names a key that was pressed. One handler can then serve many buttons, by reading event.target.
Take a guess: Can a script tell a real click from one that another script made up?
A doorbell only says "someone pressed me". A smart one also says which door, at what time, and whether it was a long press. The browser does the same: when it calls a handler, it passes in one argument, an object full of facts about what happened.
The object the browser passes to a handler, usually named event or e. event.type is the event's name, and event.target is the element where it happened.
<!DOCTYPE html>
<button id="tea">Tea</button>
<button id="coffee">Coffee</button>
<p id="out">Choose a drink</p>
<script>
function choose(event) {
document.getElementById("out").textContent = `${event.type}: ${event.target.textContent}`;
}
document.getElementById("tea").addEventListener("click", choose);
document.getElementById("coffee").addEventListener("click", choose);
</script>
Checked in Chrome
- after a press on Coffee, the page names the event and the button
One function handles both buttons. It does not need to know which button it was given to: event.target says which one was pressed. Here the kit pressed Coffee, so event.target was the Coffee button, and its text was Coffee.
Keys
For a key, the event object's key property names the key pressed: "Enter", "Escape", "a", "ArrowDown". A keydown event happens when a key goes down. Listening on document catches keys pressed anywhere on the page:
<!DOCTYPE html>
<p id="out">Press Enter to search</p>
<script>
document.addEventListener("keydown", (event) => {
if (event.key === "Enter") {
document.getElementById("out").textContent = "Searching...";
}
});
</script>
Checked in Chrome
- a press of the key a changes nothing
- a press of Enter starts the search
The kit pressed a, then Enter, by sending the page a keydown event for each. The handler ran both times, and the if let only Enter through. Testing event.key is how a page gives keys their own jobs: Escape to close a box, the arrows to move through a list.
| Property | What it holds | Example |
|---|---|---|
event.type | the event's name | "click" |
event.target | the element where the event happened | the button pressed |
event.key | for key events, the key | "Enter" |
event.target.value | for a box, the text in it | what the user has typed |
Worked example 2
A ticket counter's page has three buttons, 1, 2 and 3, for the number of tickets. One handler on all three should show Tickets: 2 when the button 2 is pressed. Write it.
What we have: three buttons whose text is the number
What we need: one handler that shows the number of the button pressed
The plan: give all three buttons the same function, and read the number from event.target
<!DOCTYPE html>
<button class="n">1</button>
<button class="n">2</button>
<button class="n">3</button>
<p id="out">Tickets: 0</p>
<script>
function pick(event) {
document.getElementById("out").textContent = `Tickets: ${event.target.textContent}`;
}
for (const button of document.querySelectorAll(".n")) {
button.addEventListener("click", pick);
}
</script>
Checked in Chrome
- after a press on the button 2, the page shows Tickets: 2
Pressing 2 shows Tickets: 2.
Check: the same function served three buttons, and the target told it which.
A path that fails: writing three handlers, one for each button, each with its number typed in. It works for three, but a page with forty seats needs forty handlers, and one typed number will be wrong.
When you are stuck: a handler cannot tell what happened
Give the handler a parameter, event, and print it: console.log(event.type, event.target);.
For keys, compare event.key with the key's name, such as "Enter", capital E included.
For one handler on many elements, read the details from event.target, not from a name outside.
A box's text is event.target.value, not its textContent.
Your turn
In a click handler, what is event.target?Tap to reveal
- The browser passes the event object to the handler.
- Its target is the element where the click happened.
The element that was clicked.
Write the condition that is true only for the Escape key.Tap to reveal
- Key events carry the key's name in event.key.
event.key === "Escape"
Why can one function handle many buttons?Tap to reveal
- The browser tells the function which element it was, through event.target.
- So the function need not be written for one button.
Because event.target says which button was pressed.
Did you know?
Which key, or which letter
A key has two names. The property event.key gives the character it typed, while event.code names the physical key, whatever its label. The code KeyQ is the Q key on a US keyboard, but the key labelled A on a French AZERTY one. So games read code, and the four keys for moving stay in one place on every layout; text boxes read key.
Why it fits here: It sharpens this topic's event.key: key reports the letter typed, and code reports where the finger pressed.
Sources: MDN: KeyboardEvent.code; W3C: UI Events KeyboardEvent code Values
Real clicks and made-up clicks
A script can make up an event and send it with dispatchEvent, and handlers run as if a person had acted. The event object tells the difference: isTrusted is true when the browser made the event, and false when a script dispatched it. The DOM standard names one old exception: a click made by the click() method comes from the browser, yet is marked false.
Why it fits here: It adds one more fact this topic's event object carries: whether the browser, or a script, caused the event.
Sources: WHATWG: DOM Standard; MDN: Event.isTrusted
In one line
The browser passes every handler an event object: event.type names the event, event.target is the element it happened on, and event.key names a key. One handler can serve many elements by reading event.target.
Typing, choosing and sending forms
At a glance
A shop's search box answers as you type: each letter narrows the list. A train booking form checks the age the moment you leave the box. A login form checks its fields before anything is sent. Each of these listens for a different event.
The input event happens at every change to a box, change happens when a choice is made, and submit happens when a form is sent. A box's text is in its value. To keep the page when a form is sent, listen for submit on the form and call event.preventDefault() first.
Take a guess: Can a form be sent without anyone clicking its button?
A shop's search box answers as you type: each letter narrows the list. A form for a train booking checks the age the moment you leave the box. A login form checks its fields before anything is sent. Each of these listens to a different event.
| Event | Happens when | Read |
|---|---|---|
"input" | the text in a box changes, at every letter | event.target.value |
"change" | a choice is made: a select is changed, a box is left after editing, a checkbox is ticked | event.target.value or .checked |
"submit" | a form is sent, by its button or by Enter | the form's fields |
As you type: input
A box's text is its value. The input event happens at every change, so a handler can answer letter by letter. This one counts the letters of a message, as an SMS form does:
<!DOCTYPE html>
<input id="msg">
<p id="out">0 letters</p>
<script>
document.getElementById("msg").addEventListener("input", (event) => {
document.getElementById("out").textContent = `${event.target.value.length} letters`;
});
</script>
Checked in Chrome
- after Namaste was typed into the box, the page counts 7 letters
A choice made: change
<!DOCTYPE html>
<select id="city">
<option>Pune</option>
<option>Nagpur</option>
</select>
<p id="out">Delivery to Pune</p>
<script>
document.getElementById("city").addEventListener("change", (event) => {
document.getElementById("out").textContent = `Delivery to ${event.target.value}`;
});
</script>
Checked in Chrome
- after Nagpur was chosen, the page names it
Sending a form: submit, and preventDefault
When a form is sent, the browser's own job, its default action, is to leave the page and load the form's address with the fields attached, as the forms lesson of the HTML step showed. A page that checks the fields, or sends them itself, must stop that. event.preventDefault() in a submit handler tells the browser not to do its default action:
A method of the event object that cancels the browser's own action for the event: for a form's submit, leaving the page; for a link's click, following it.
<!DOCTYPE html>
<form id="f">
<input id="age" value="15">
<button>Book</button>
</form>
<p id="out"></p>
<script>
document.getElementById("f").addEventListener("submit", (event) => {
event.preventDefault();
const age = Number(document.getElementById("age").value);
document.getElementById("out").textContent = age >= 18 ? "Booked" : "Bookings need an adult";
});
</script>
Checked in Chrome
- after the form was sent with the age 15, the page asks for an adult
- and the browser was told not to leave the page
Listen for submit on the form, not for click on its button. The form is sent by a press of Enter in a box as well as by the button, and only submit catches both. And the value of a box is always text, as the values lesson warned, so the age was converted with Number before comparing.
Worked example 3
A school's sign-up form has a name box. When it is sent with an empty name, it should stay on the page and say Please type your name; otherwise it should say Thank you, and the name.
What we have: a form with one box
What we need: the right message, and no leaving the page
The plan: listen for submit, call preventDefault first, then check the trimmed value
<!DOCTYPE html>
<form id="f">
<input id="name" value=" ">
<button>Join</button>
</form>
<p id="out"></p>
<script>
document.getElementById("f").addEventListener("submit", (event) => {
event.preventDefault();
const name = document.getElementById("name").value.trim();
document.getElementById("out").textContent = name === "" ? "Please type your name" : `Thank you, ${name}`;
});
</script>
Checked in Chrome
- a name of only spaces is treated as empty
- with Asha typed, the page thanks her
An empty name gives Please type your name; Asha gets Thank you, Asha.
Check: trim turned a name of spaces into the empty string, as the values lesson showed.
A path that fails: listening for click on the Join button. A visitor who presses Enter in the box sends the form without touching the button, and the check is skipped.
When you are stuck: a box or a form does not answer
For typing, listen for input; for a finished choice, change; for a form, submit on the form itself.
Read a box's text with .value, and convert it with Number before any arithmetic.
If the page reloads when a form is sent, the handler did not call event.preventDefault(), or called it after an error.
Call preventDefault as the first line of a submit handler, so that a later error does not let the form leave.
Your turn
Which event answers at every letter typed into a box?Tap to reveal
- input happens each time the text changes.
- change waits until the box is left.
"input".
What does event.preventDefault() do in a submit handler?Tap to reveal
- The browser's default action for a submit is to leave the page with the form's data.
- preventDefault cancels that action.
It keeps the form from leaving the page.
Why listen for submit on the form rather than click on its button?Tap to reveal
- Enter in a box sends the form too.
- Only submit catches every way the form is sent.
Because a form can be sent without its button.
Did you know?
Enter sends the form
A form can be sent without a click. The HTML standard calls it implicit submission: on some platforms, pressing Enter in a text box submits the form. If the form has a submit button, the browser fires a click at it. If it has none, a form with a single text box is sent all the same, with no click anywhere. Only the form's submit event is sure to hear every case.
Why it fits here: It explains this topic's advice to listen for submit on the form: Enter can send a form without any button being pressed.
A send that skips the listener
Calling form.submit() from a script sends a form quietly. MDN lists the differences: no submit event is raised, so submit listeners never run, and the browser's checks on the fields are not triggered. The newer requestSubmit() behaves like pressing the form's submit button, events and checks included, and has worked across browsers since September 2022.
Why it fits here: It warns about this topic's submit listener: a form sent by form.submit() never fires it, so its checks are skipped.
Sources: MDN: HTMLFormElement.submit(); MDN: HTMLFormElement.requestSubmit(); WHATWG: HTML Standard, form submission
In one line
input happens at every change to a box, change when a choice is made, and submit when a form is sent. Read a box's text from its value, listen for submit on the form, and call event.preventDefault() first to keep the page.
How an event travels: bubbling
At a glance
Drop a pebble into a pond, and the ripple spreads outward, ring after ring. An event on a page spreads too. A click on a button is also a click on the card around it, on the section around the card, and on the body.
Most events bubble: after the element where they happen, every element above it hears them, from the inside out. The property event.target is where the event started, and event.currentTarget is where it has reached now. The method event.stopPropagation() stops it rising any further.
Take a guess: Before bubbling, which way did some browsers send an event through the tree?
Drop a pebble into a pond, and the ripple spreads outward, ring after ring. An event on a page spreads too. A click on a button is also a click on the card around the button, and on the section around the card, and on the body. The browser tells each of them, in turn, from the inside out.
The way most events, once they have happened on an element, are then passed to its parent, then to that parent's parent, and so on up to the document, like a bubble rising. A listener on any of those elements hears the event.
<!DOCTYPE html>
<div id="card">
<button id="b">Remind me</button>
</div>
<script>
const order = [];
document.getElementById("b").addEventListener("click", () => order.push("button"));
document.getElementById("card").addEventListener("click", () => order.push("card"));
document.body.addEventListener("click", () => order.push("body"));
</script>
Checked in Chrome
- one press on the button ran three handlers: the button's, then the card's, then the body's
The kit pressed only the button, yet three handlers ran, in the order the event bubbled: button, card, body. Each handler was told about the same click. That is why a click on a button inside a card that opens when clicked can open the card as well, which is sometimes what you want and sometimes a bug.
target and currentTarget
As the event bubbles, event.target stays the element where it started, the button. A second property, event.currentTarget, is the element whose listener is running now. In the card's handler, target is the button and currentTarget is the card:
<!DOCTYPE html>
<div id="card">
<button id="b">Remind me</button>
</div>
<script>
const seen = [];
document.getElementById("card").addEventListener("click", (event) => {
seen.push(event.target.id, event.currentTarget.id);
});
</script>
Checked in Chrome
- in the card's handler, the target was the button b and the current target was the card
Stopping the bubble
event.stopPropagation() in a handler stops the event from going any further up. The handlers above that point never hear it:
<!DOCTYPE html>
<div id="card">
<button id="b">Remind me</button>
</div>
<script>
const order = [];
document.getElementById("b").addEventListener("click", (event) => {
order.push("button");
event.stopPropagation();
});
document.getElementById("card").addEventListener("click", () => order.push("card"));
</script>
Checked in Chrome
- with stopPropagation, only the button's handler ran
A common mistake
Reaching for stopPropagation to fix every surprise. It also hides the event from listeners you did not write, such as a page's analytics or a menu that closes when you click elsewhere. Often the better fix is in the outer handler: check event.target, and do nothing when the click came from the button.
Not every event bubbles. Most do, click, input, keydown and submit among them. A few, such as focus, do not; MDN's page for each event says whether it bubbles.
Worked example 4
A product card on a shop's page opens the product's page when clicked anywhere. Its Add to cart button must add the item without opening the page. Write the two handlers, with the card's handler ignoring clicks that came from the button.
What we have: a card with a button inside it
What we need: a click on the button adds to the cart and does not open the product
The plan: both listen for click; the card's handler checks event.target and returns early when it is the button
<!DOCTYPE html>
<div id="card">
<p>Masala tea, ₹120</p>
<button id="add">Add to cart</button>
</div>
<script>
const log = [];
document.getElementById("add").addEventListener("click", () => log.push("added"));
document.getElementById("card").addEventListener("click", (event) => {
if (event.target.id === "add") return;
log.push("opened");
});
</script>
Checked in Chrome
- a press on the button only added to the cart
- a click on the card's text opened the product
The button adds; a click elsewhere on the card opens.
Check: the second check clicked the card's paragraph, and the card's handler ran, as the target was not the button.
Another way: call event.stopPropagation() in the button's handler. It works here, but hides the click from every listener above the card as well.
When you are stuck: a click runs a handler you did not expect
Remember bubbling: a click on an inner element reaches every listener above it.
Print event.target and event.currentTarget in each handler to see where the click started and where it is now.
In an outer handler, return early when event.target is an inner element with its own job.
Use stopPropagation only when no listener above should hear the event.
Your turn
A page has listeners for click on a button, on its card and on the body. One press on the button: in what order do they run?Tap to reveal
- The event happens on the button first.
- Then it bubbles to the card, then to the body.
Button, card, body.
In the card's handler, after a click on its button, what are event.target and event.currentTarget?Tap to reveal
- target stays where the event started: the button.
- currentTarget is the element whose listener is running: the card.
target is the button; currentTarget is the card.
What does event.stopPropagation() do?Tap to reveal
- It stops the event from bubbling further up.
- Listeners above it never hear the event.
It stops the bubbling at that element.
Did you know?
Down first, then up
Bubbling settled a quarrel between browsers. Netscape sent an event from the outer element to the inner one, which is called capturing; Microsoft sent it from the inner element out, which is bubbling. The W3C took a middle position: an event is first captured down to its target, and then bubbles up again. The DOM standard keeps both, as a capturing phase and a bubbling phase.
Why it fits here: It shows the hidden half of this topic's bubbling: before an event rises, it first travels down from the top to its target.
Sources: QuirksMode: Event order; Wikipedia: DOM event; WHATWG: DOM Standard
Gone when the handler ends
The property currentTarget lives only while a handler runs. MDN warns that outside an event handler it will be null, and the DOM standard's dispatch ends by setting the event's currentTarget to null. So an event kept in a variable and read after the handler has finished shows currentTarget as null, even though it pointed at an element a moment before.
Why it fits here: It warns about this topic's currentTarget: read it inside the handler, because once the handler ends, it is gone.
Sources: MDN: Event.currentTarget; WHATWG: DOM Standard
In one line
Most events bubble: after the element where they happen, every element above it hears them, from the inside out. event.target is where it started, event.currentTarget is where it is now, and stopPropagation stops it rising.
One listener for many: delegation
At a glance
A school does not hire one guard for each student. One guard at the gate sees everyone who comes and goes, including students who joined this morning. Bubbling makes the same thing possible on a page.
One listener on a parent hears the events of all its children, even children added later. This is called event delegation. Inside the listener, event.target is where the event started, and event.target.closest("li") climbs to the nearest list item. One listener then covers every child, and a new item needs nothing attached.
Take a guess: Can one listener on a form hear when each of its boxes gets focus?
A school does not hire one guard for each student. One guard at the gate sees everyone who comes and goes, including students who joined this morning. Bubbling makes the same thing possible on a page: one listener on a parent hears the events of all its children, even children added later.
The second bug of the story was this. Each Remind me button had its own listener, attached when the page loaded. A ferry added in the afternoon got a new button, and nobody attached a listener to it:
<!DOCTYPE html>
<ul id="ferries">
<li data-time="4.15">4.15 <button>Remind me</button></li>
<li data-time="5.30">5.30 <button>Remind me</button></li>
</ul>
<script>
const reminded = [];
for (const button of document.querySelectorAll("#ferries button")) {
button.addEventListener("click", (event) => {
reminded.push(event.target.parentNode.dataset.time);
});
}
</script>
Checked in Chrome
- the kit added a third ferry, at 6.45, after the listeners were set up
- a press on the new button did nothing; only the old 4.15 button was heard
The buttons carry their ferry's time in a data-time attribute, which a script reads as dataset.time. The page's own data, kept on its elements like this, is a common pattern.
Listening on a parent instead of on each child, and using event.target to find which child the event came from. Children added later are covered too, because their events bubble up to the same parent.
<!DOCTYPE html>
<ul id="ferries">
<li data-time="4.15">4.15 <button>Remind me</button></li>
<li data-time="5.30">5.30 <button>Remind me</button></li>
</ul>
<script>
const reminded = [];
document.getElementById("ferries").addEventListener("click", (event) => {
const button = event.target.closest("button");
if (!button) return;
reminded.push(button.closest("li").dataset.time);
});
</script>
Checked in Chrome
- the kit added the 6.45 ferry after the listener was set up
- a press on the new button was heard, by the one listener on the list
Read the handler line by line. The listener is on the list. event.target.closest("button") walks up from wherever the click started to the nearest button, or gives null if the click was not on a button, for example on the time's text. The early return ignores those clicks. Then button.closest("li") finds the row, and its data gives the time.
A method of every element that gives the nearest element, itself or one of its ancestors, that matches a CSS selector, or null if none does.
Delegation also saves work: a list of five hundred rows needs one listener, not five hundred. And it fits the render function of the DOM lesson, which empties and rebuilds a list: the rows are thrown away and made again, but the listener on the list, which was never thrown away, still hears them.
Worked example 5
A cart lists items, each with a Remove button. Items are added while the visitor shops. Write one listener that removes the right item when its button is pressed, and check it on an item added after the listener.
What we have: a list whose items are added later, each with a button
What we need: a press removes that item only
The plan: delegate: one click listener on the list, closest to find the button and its item, then remove the item
<!DOCTYPE html>
<ul id="cart"></ul>
<script>
const cart = document.getElementById("cart");
cart.addEventListener("click", (event) => {
const button = event.target.closest("button");
if (!button) return;
button.closest("li").remove();
});
for (const name of ["rice", "dal", "oil"]) {
const li = document.createElement("li");
li.textContent = `${name} `;
const remove = document.createElement("button");
remove.textContent = "Remove";
li.append(remove);
cart.append(li);
}
</script>
Checked in Chrome
- a press on dal's button removed dal, and only dal
Pressing dal's button leaves rice and oil.
Check: the items were made after the listener, yet the one listener heard the press.
A path that fails: attaching a listener to each button inside the loop that makes them. It works for these three, but every item added later by other code needs its own listener, and the day one is forgotten is the day of the story's silent buttons.
When you are stuck: buttons added later do not answer
Listeners attached to elements at load cover only those elements. Delegate to a parent that is always there.
In a delegated handler, find the element with event.target.closest("button"), as the click may start on a child of the button.
Return early when closest gives null: the click was elsewhere in the parent.
Keep the element's own data on it, in data- attributes, and read it with dataset.
Your turn
Why does one listener on a list hear clicks on buttons added to the list later?Tap to reveal
- Clicks on the buttons bubble up to the list.
- The listener is on the list, which was there all along.
Because the clicks bubble up to the list.
What does event.target.closest("li") give?Tap to reveal
- It starts from the element where the click happened.
- It walks up to the nearest li, itself included.
The nearest li at or above the clicked element, or null.
How does a script read <li data-time="4.15">'s time?Tap to reveal
- data- attributes appear on the element's dataset object.
- data-time becomes dataset.time.
li.dataset.time gives 4.15.
Did you know?
Now and in the future
Delegation became famous through a library. jQuery 1.3 added a method called .live(), which attached a handler for all elements matching a selector, now and in the future. Its documentation explains how: it attached delegated handlers to the document itself. jQuery deprecated .live() in version 1.7 and removed it in 1.9, asking people to use .on() instead.
Why it fits here: It shows how old this topic's trick is: a popular library built a whole method on one listener at the top of the page.
Events that stay put
Delegation needs bubbling, and not every event bubbles. MDN notes that focus does not bubble, but the related focusin event that follows it does; blur and focusout are the same kind of pair. So one listener on a form cannot hear focus on each box, but it can hear focusin. javascript.info adds a historical twist: focus and blur still travel down in the capturing phase.
Why it fits here: It marks the limit of this topic's trick: an event that does not bubble never rises to the parent's listener.
Sources: MDN: Element: focus event; MDN: Element: blur event; javascript.info: Focusing: focus/blur
In one line
Event delegation listens on a parent and uses event.target, with closest, to find the child the event came from. One listener then covers every child, those added later included.
Removing listeners, once, and onclick
At a glance
A shop's Pay button must work once. A second press, while the bank thinks, would pay twice. So pages need to turn listeners off as well as on.
The option { once: true } makes a listener remove itself after its first run. The method removeEventListener takes off the very function that was added, so a handler to be removed must be kept in a name. The older onclick property holds only one handler, and a second assignment replaces the first. That is why addEventListener is preferred.
Take a guess: Can one call take off a dozen listeners at once, arrow functions included?
A shop's Pay button must work once. A second press, while the bank thinks, would pay twice. Pages need to turn listeners off as well as on.
Once only
A third argument to addEventListener can hold options. { once: true } removes the listener after its first run:
<!DOCTYPE html>
<button id="b">Pay ₹450</button>
<script>
let payments = 0;
document.getElementById("b").addEventListener("click", () => {
payments++;
}, { once: true });
</script>
Checked in Chrome
- three presses made one payment
A real payment page does more: it also disables the button with button.disabled = true, so that the visitor can see that the press was taken.
removeEventListener
removeEventListener takes a listener off. It needs the same event name and the very same function that was added, so the handler must have a name:
<!DOCTYPE html>
<button id="b">Count</button>
<script>
let count = 0;
function add() {
count++;
}
const button = document.getElementById("b");
button.addEventListener("click", add);
button.click();
button.removeEventListener("click", add);
button.click();
</script>
Checked in Chrome
- the press before removeEventListener counted, and the press after it did not
A common mistake
Removing with a new arrow function. button.removeEventListener("click", () => { count++; }) removes nothing, because that arrow is a new function, not the one that was added, even though it looks the same. Keep the handler in a name, and pass that name to both calls.
onclick, the older way
Elements also have properties such as onclick, and assigning a function to one makes it the handler. You will meet it in older code and in short examples. The difference: a property holds one function, so a second assignment replaces the first, while addEventListener adds as many listeners as you like:
<!DOCTYPE html>
<button id="b">Go</button>
<script>
const ran = [];
const button = document.getElementById("b");
button.onclick = () => ran.push("first");
button.onclick = () => ran.push("second");
button.addEventListener("click", () => ran.push("third"));
button.addEventListener("click", () => ran.push("fourth"));
</script>
Checked in Chrome
- one press ran the second onclick, which had replaced the first, and both added listeners
Two scripts that each set onclick on the same button fight, and the last one wins without a word, like the shared globals of the scope lesson. Prefer addEventListener, which lets them live side by side.
| Way | How many handlers | Remove with |
|---|---|---|
addEventListener("click", f) | as many as are added | removeEventListener("click", f) |
addEventListener("click", f, { once: true }) | one, for one run | removes itself |
el.onclick = f | one; a new one replaces it | el.onclick = null |
Worked example 6
A quiz shows a question with three answer buttons. The first press is the answer: it must show Right or Wrong, and every press after it must be ignored. The right answer is B. Write it with once.
What we have: three buttons, one of them right, and a result line
What we need: only the first press counts
The plan: one listener with once on the group of buttons, reading the button from event.target
<!DOCTYPE html>
<div id="answers">
<button>A</button>
<button>B</button>
<button>C</button>
</div>
<p id="out"></p>
<script>
document.getElementById("answers").addEventListener("click", (event) => {
const choice = event.target.textContent;
document.getElementById("out").textContent = choice === "B" ? "Right" : "Wrong";
}, { once: true });
</script>
Checked in Chrome
- the first press, C, gave Wrong, and the later press on B was ignored
The first press decides: Wrong for C, and B afterwards changes nothing.
Check: the listener removed itself after the first press, so the second press found no listener.
A path that fails: writing a flag by hand, such as let answered = false;, and forgetting to set it inside the handler. once does the job with nothing to forget.
When you are stuck: a listener will not go away, or runs twice
removeEventListener needs the same function: keep the handler in a name.
If a handler runs twice per press, it was added twice, for example by code that runs each time a list is rebuilt.
For a job that must happen once, use { once: true }.
If a handler vanished, look for a later onclick assignment that replaced it.
Your turn
Why does b.removeEventListener("click", () => go()) not remove a listener added as b.addEventListener("click", () => go())?Tap to reveal
- Each arrow written is a new function.
- removeEventListener removes only the very same function that was added.
Because the two arrows are different functions.
After el.onclick = f; el.onclick = g;, what runs at a click?Tap to reveal
- onclick holds one function.
- The second assignment replaced f with g.
Only g.
Which option makes a listener run only the first time?Tap to reveal
- The third argument holds options.
{ once: true }.
Did you know?
One signal removes them all
Taking listeners off once needed a name for every handler. The signal option changes that: MDN explains that a listener added with a signal is removed when the abort() method of its AbortController is called. The DOM standard does it with abort steps attached to each listener. One controller can serve many listeners, so a single abort() removes them all, arrow functions included.
Why it fits here: It solves this topic's arrow problem: a listener added with a signal can be removed without keeping its function in a name.
Sources: MDN: EventTarget.addEventListener(); WHATWG: DOM Standard
A list of every listener
Chrome's console can show the listeners on any element. Its Console Utilities include getEventListeners(object), which returns the listeners registered on an object, grouped by event type, such as click or keydown. These utilities work only when typed into the DevTools Console, not in a page's own scripts. So checking that a listener was really removed takes one line.
Why it fits here: It gives a way to check this topic's removals: list an element's listeners before and after, and see the handler gone.
Source: Chrome for Developers: Console Utilities API reference
In one line
removeEventListener takes off the very function that was added, so keep handlers in names; { once: true } makes a listener remove itself after one run. The onclick property holds one handler, which a second assignment replaces, so prefer addEventListener.
Where it is used
Every page that answers a person uses events. Here is where each idea of this lesson shows up in real work.
| What you learned | Where it is used | A real example |
|---|---|---|
| click listeners | every button and link a script handles | a Remind me button that sets a reminder |
| the event object | one handler for many controls | a keypad whose digits all share one handler |
| key events | shortcuts and keyboard use | Escape closes a pop-up; the arrows move through search suggestions |
| input | answering as people type | a search box that narrows the list at every letter |
| submit and preventDefault | forms checked or sent by the page itself | a sign-up form that checks the fields before anything is sent |
| bubbling | listeners on containers | a card that opens when clicked anywhere |
| delegation | lists that change | a chat whose messages, added all the time, each have a Reply button |
| once and removeEventListener | jobs that must not repeat | a Pay button that takes one press |
Mistakes and debugging
These are the slips that people meet most often with events. The notes under each page say what the kit did in Chrome and what it found.
1. Brackets on the handler
<!DOCTYPE html>
<button id="b">Go</button>
<p id="out">0</p>
<script>
let n = 0;
function go() {
n++;
document.getElementById("out").textContent = n;
}
document.getElementById("b").addEventListener("click", go());
</script>
Checked in Chrome
- the handler ran once at load, and the press did nothing
The fix: addEventListener("click", go).
2. A form that leaves the page
A submit handler without event.preventDefault() runs, and then the browser sends the form and loads a new page, wiping out whatever the handler showed. The fix: call preventDefault as the handler's first line.
3. Listening on the button instead of the form
A click listener on a form's button misses the form being sent by Enter. The fix: listen for submit on the form.
4. Listeners on children that come later
<!DOCTYPE html>
<ul id="list"><li><button>Old</button></li></ul>
<script>
const heard = [];
for (const b of document.querySelectorAll("#list button")) {
b.addEventListener("click", () => heard.push(b.textContent));
}
const li = document.createElement("li");
li.innerHTML = "<button>New</button>";
document.getElementById("list").append(li);
</script>
Checked in Chrome
- the new button was pressed, and nothing heard it
The fix: delegate: one listener on the list, with event.target.closest("button").
5. A box's text used as a number
<!DOCTYPE html>
<input id="qty" value="2">
<p id="out"></p>
<script>
document.getElementById("qty").addEventListener("input", (event) => {
document.getElementById("out").textContent = event.target.value + 1;
});
</script>
Checked in Chrome
- typing 3 showed 31: the text 3 joined with 1
The fix: Number(event.target.value) + 1.
6. removeEventListener with a new function
<!DOCTYPE html>
<button id="b">Count</button>
<script>
let count = 0;
const button = document.getElementById("b");
button.addEventListener("click", () => count++);
button.removeEventListener("click", () => count++);
</script>
Checked in Chrome
- the listener was not removed: the press still counted
The fix: keep the handler in a name, and pass the name to both calls.
The debugging corner: is the handler running at all?
For any event bug, first find out whether the handler runs: put console.log("click heard", event.target); as its first line. If nothing is printed, the listener is on the wrong element, has the wrong event name, or was never added. If it prints at load, the handler was called with brackets. In the Sources panel of the DevTools step, the Event Listener Breakpoints pane can pause on every click, wherever its listener is.
Quick card
The whole lesson on one card. Come back to it whenever you need a reminder.
The lesson in code
<!DOCTYPE html>
<form id="f">
<input id="name">
<button>Join</button>
</form>
<ul id="list">
<li><button data-id="1">Remind me</button></li>
</ul>
<p id="out"></p>
<script>
// submit on the form; preventDefault keeps the page
document.getElementById("f").addEventListener("submit", (event) => {
event.preventDefault();
document.getElementById("out").textContent = `Hello, ${document.getElementById("name").value}`;
});
// delegation: one listener on the list; closest finds the button
const reminded = [];
document.getElementById("list").addEventListener("click", (event) => {
const button = event.target.closest("button");
if (!button) return;
reminded.push(button.dataset.id);
});
</script>
Checked in Chrome
- sending the form with Asha typed greets her, on the same page
- a press on Remind me was heard by the list's one listener
| When you see | It means | Look at |
|---|---|---|
| a handler that runs at load and never again | brackets on the handler | pass the function: f, not f() |
| nothing at all on a press | the wrong element, the wrong event name, or no listener | a console.log in the handler |
| the page reloads when a form is sent | no preventDefault | the submit handler's first line |
| new buttons that never answer | listeners added before the buttons | delegation |
| a handler running for clicks elsewhere | bubbling | event.target in the outer handler |
| 31 where 4 was wanted | a box's text joined with a number | Number(event.target.value) |
The story: One bell, when asked
You find the line that was meant to say "when this button is pressed, ring". It said "ring", there and then, as the panel woke, and handed the button nothing to remember. You give it the job itself, not the job's answer. Then you move the listening from each button to the panel as a whole, so that buttons added later are heard as well.
A passenger presses Remind me, and one bell rings, for her ferry only.
Master Verge nods. "Now it listens," he says. "Next, you must learn what to do when it hears something it did not expect."
Reagents gathered: event, addEventListener, event.target, preventDefault, bubbling, delegation.
Sources
- MDN Web Docs (Prose CC BY-SA 2.5 or later; code samples added since 2010-08-20 CC0 (its licensing page, read 2026-10-26); reused with credit)
- HTML Living Standard (WHATWG) (CC BY 4.0: "Copyright WHATWG (Apple, Google, Mozilla, Microsoft). This work is licensed under a Creative Commons Attribution 4.0 International License" (its acknowledgements page, read 2026-10-26); reused with credit)