19.1 Listening for Events
Before you start, make a new Vite project for today exactly as you did on Day 18: run npm create vite@latest day19 in a terminal, pick the vanilla TypeScript template, then cd day19, npm install, and npm run dev. Every example today comes in two parts. The first part, shown with a name like bell.html, is the page: put it inside the <body> of index.html, in place of what the template put there, and keep the <script type="module" src="/src/main.ts"> line after it. The second part, shown with a name like bell.dom.ts, is the script: it replaces everything in src/main.ts. Lines printed with console.log appear in the browser’s developer tools, in the Console tab (press F12, or right-click the page and choose Inspect).
On Day 18, every script ran once, from top to bottom, as the page loaded, and then it was finished. It could build a list or change some text, but once it reached its last line, nothing the user did could make it run again. A page that does something when you click a button needs a way to say “later, when this happens, run this code”.
The browser gives you that. Everything the user does on a page, such as clicking, pressing a key, or typing in a box, is reported as an event: a message from the browser saying “this just happened to this element”. You can ask the browser to call one of your functions every time a certain event happens to a certain element. That request is called adding an event listener, and the function is the event handler (people also call the function itself the listener).
Think of a doorbell. Wiring the bell to the button is something you do once; the bell then rings each time someone presses the button, whenever that is, as many times as they like. addEventListener is the wiring.
element.addEventListener("click", handler);
Take it apart:
elementis the element to watch, found withquerySelectoras on Day 18."click"is the event type, a string that names which event to listen for."click","keydown"(a key goes down), and"input"(the text in a box changes) are the three you will use today.handleris a function. It is passed, not called: there are no parentheses after it. The browser calls it later, once for each event, the same waymapcalled the callback you gave it on Day 11.
Worked example: A bell that counts its rings
The page has a button and a paragraph:
<button id="ring" type="button">Ring the bell</button>
<p id="status">The bell has not rung.</p>The script finds both, checks that neither is null, and wires the button to a handler:
const ringButton = document.querySelector<HTMLButtonElement>("#ring");
const status = document.querySelector<HTMLParagraphElement>("#status");
if (ringButton === null || status === null) {
throw new Error("The page is missing #ring or #status");
}
let rings = 0;
ringButton.addEventListener("click", () => {
rings = rings + 1;
status.textContent = `The bell has rung ${rings} times.`;
console.log("Ding!");
});
console.log("Listener attached");Read it in the order the browser runs it:
| When | What runs | What happens |
|---|---|---|
| Page loads | Lines 1–5 | Both elements are found; neither is null, so nothing is thrown |
| Page loads | Line 7 | rings starts at 0 |
| Page loads | Lines 9–13 | The handler is attached: stored by the browser, not run |
| Page loads | Line 15 | Listener attached is printed; the script has reached its end |
| First click | Lines 10–12 | rings becomes 1, the text changes, Ding! is printed |
| Second and third clicks | Lines 10–12, twice more | rings becomes 2, then 3 |
After three clicks the console shows:
Listener attached
Ding!
Ding!
Ding!and the paragraph reads The bell has rung 3 times. Notice that Listener attached comes first, even though line 15 is below the handler. Lines 10 to 12 are inside a function, and a function’s body runs only when it is called. The browser calls it on each click, long after the script has finished.
Notice also that rings keeps its value between clicks. It was declared outside the handler, at the top level of the script, so it lives as long as the page does. Each click adds 1 to the number the last click left there. If let rings = 0; were inside the handler, every click would make a fresh rings at 0 and the text would always say 1.
Key idea
element.addEventListener(type, handler) asks the browser to call handler each time an event of that type happens
to that element. Attaching runs nothing; the handler’s body runs later, once per event.
Watch out
Calling the handler instead of passing it. Parentheses after the handler’s name call it:
const ringButton = document.querySelector<HTMLButtonElement>("#ring");
if (ringButton === null) throw new Error("The page is missing #ring");
const ring = (): void => {
console.log("Ding!");
};
ringButton.addEventListener("click", ring());called-handler.dom.ts:8:38 - error TS2769: No overload matches this call.
Overload 1 of 2, '(type: "click", listener: (this: HTMLButtonElement, ev: PointerEvent) => any, options?: boolean | AddEventListenerOptions | undefined): void', gave the following error.
Argument of type 'void' is not assignable to parameter of type '(this: HTMLButtonElement, ev: PointerEvent) => any'.
Overload 2 of 2, '(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions | undefined): void', gave the following error.
Argument of type 'void' is not assignable to parameter of type 'EventListenerOrEventListenerObject'.ring() on line 8 runs ring once, right now, and passes what it returns to addEventListener. ring returns nothing (void, Day 8), and addEventListener needs a function, so the checker rejects it. The message is long because addEventListener has two overloads, two different lists of parameters it accepts, and the checker reports why each one failed; the line that matters is Argument of type 'void' is not assignable to parameter of type …. The fix is to drop the parentheses: pass the function, ring, and let the browser call it. Undo this in main.ts once you have read the message.
Pause and try
Question 1 · Tracing
This script runs on a page with one button, <button id="go" type="button">Go</button>. The user clicks the button twice. Predict everything the console shows, in order.
const goButton = document.querySelector<HTMLButtonElement>("#go");
if (goButton === null) throw new Error("The page is missing #go");
console.log("one");
goButton.addEventListener("click", () => {
console.log("two");
});
console.log("three");Check your reasoning
one
three
two
two- As the page loads, line 4 prints
one. - Lines 5 to 7 attach the handler; nothing inside it runs yet.
- Line 8 prints
three, and the script ends. - Each click calls the handler, which prints
two. Two clicks, two lines.
If you put two second, you read the handler as if it ran where it is written. It runs when the event happens.
Reread 19.1 Listening for Events if your order differed.
19.2 Event Types
When the browser calls a handler, it passes it one argument: an event object describing what happened. Different events carry different details. A click knows where on the screen the pointer was; a key press knows which key it was. So event objects come in several types, and the checker needs to know which one your handler gets.
You never have to say. addEventListener knows which event object goes with each event-type string, so the handler’s parameter is contextually typed, the same way Day 11’s callbacks got their parameter types from the array:
| Event type string | Handler’s parameter type | Useful properties |
|---|---|---|
"click" |
PointerEvent |
type, target, clientX, clientY |
"keydown" |
KeyboardEvent |
type, target, key |
"input" |
Event |
type, target |
Three names to learn. Event is the most general: every event object has a type (the event-type string, such as "input") and a target (19.3). MouseEvent adds the mouse details, such as the pointer position. KeyboardEvent adds key, the key that was pressed, as a string: "a", "Enter", "Escape", "ArrowUp". A click is reported with PointerEvent, a newer, more detailed kind of MouseEvent that also covers touch screens and pens. Anything a MouseEvent has, a PointerEvent has too, so a handler written for a MouseEvent works for clicks.
Worked example: Reporting each key
This listener goes on document, the whole page, so it hears every key press wherever it happens:
<p>Press any key.</p>
<p id="last">No key pressed yet.</p>const last = document.querySelector<HTMLParagraphElement>("#last");
if (last === null) throw new Error("The page is missing #last");
document.addEventListener("keydown", (event) => {
last.textContent = `You pressed ${event.key}`;
console.log(event.type, event.key);
});Hover over event on line 4 in VS Code and it shows (parameter) event: KeyboardEvent. That is why event.key on line 5 is allowed. Press a, then Enter, then the up arrow, and the console shows:
keydown a
keydown Enter
keydown ArrowUpThe paragraph ends up reading You pressed ArrowUp. A letter key gives the letter itself; other keys give a name, such as Enter or ArrowUp. Those names are fixed strings, so you compare against them exactly, with a capital letter.
Now vary one thing: write the handlers as separate named functions instead of inline. Then the parameter has nothing to take its type from, so you annotate it yourself, and the three type names appear in your code:
<button id="save" type="button">Save</button>
<input id="title">
<p id="log"></p>const saveButton = document.querySelector<HTMLButtonElement>("#save");
const titleInput = document.querySelector<HTMLInputElement>("#title");
const log = document.querySelector<HTMLParagraphElement>("#log");
if (saveButton === null || titleInput === null || log === null) {
throw new Error("The page is missing an element");
}
const handleSave = (event: MouseEvent): void => {
log.textContent = `Saved (${event.type})`;
};
const handleTyping = (event: Event): void => {
log.textContent = `Typing (${event.type})`;
};
const handleKey = (event: KeyboardEvent): void => {
console.log(`Key: ${event.key}`);
};
saveButton.addEventListener("click", handleSave);
titleInput.addEventListener("input", handleTyping);
document.addEventListener("keydown", handleKey);Type Notes in the box, press s while in it, and click Save. The paragraph shows Typing (input) while you type and Saved (click) after the click, and the console shows:
Key: s
Line 8 annotates the click handler as taking a MouseEvent. The browser will pass it a PointerEvent, and that is fine: a PointerEvent has everything a MouseEvent has, so the checker accepts line 20. Line 12 uses plain Event because an "input" event carries nothing extra. Each handler is a const holding an arrow function, as on Day 8, rather than a function declaration; 19.4 explains why that matters on a page.
Watch out
Reading a property the event does not have. A click has no key, so asking a click event for one is a type error:
const button = document.querySelector<HTMLButtonElement>("#ring");
if (button === null) throw new Error("No #ring button on the page");
button.addEventListener("click", (event) => {
console.log(`You pressed ${event.key}`);
});wrong-event.dom.ts:5:36 - error TS2339: Property 'key' does not exist on type 'PointerEvent'.The message is Day 7’s “no such property”, and it names the event type, which tells you which event you are really handling. If you meant to react to a key, listen for "keydown" instead. Undo this in main.ts once you have read the message.
Key idea
The event-type string decides the handler’s parameter type: "click" gives a PointerEvent (a kind of MouseEvent),
"keydown" gives a KeyboardEvent with a key, and "input" gives a plain Event. Inline handlers get the type
automatically; a separate handler needs an annotation.
Pause and try
Question 2 · Multiple choice
box is an HTMLInputElement. In box.addEventListener("keydown", (event) => { … }), what type does the checker give event?
EventKeyboardEventHTMLInputElementany, because the parameter has no annotation
Check your reasoning
B. The event-type string "keydown" decides the parameter type, and a key event is a KeyboardEvent, which is why event.key is allowed.
- A is wrong because
Eventis what an"input"event gives. AKeyboardEventis a more detailed kind ofEvent. - C is wrong because the parameter is the event object, not the element. The element is
boxitself. - D is wrong because the parameter is contextually typed from
addEventListener, just as amapcallback’s parameter is typed from the array.
Reread 19.2 Event Types if you chose differently.
19.3 Narrowing the Event Target
Every event object has a target property: the element the event actually happened to. Why would you need it, when you already have the element in a variable? Because one handler can serve many elements. A handler attached to three buttons needs to know which of the three was clicked, and event.target tells it.
There is a catch, and it comes from the checker. Hover over target and you see its type: EventTarget | null. An EventTarget is anything that can receive events, which includes elements but also the whole window and other objects that are not elements at all. The checker cannot know in advance what the target will be, so it gives the most general type, and it adds null because some events have no target. Neither type has a value or a textContent.
const nameInput = document.querySelector<HTMLInputElement>("#name");
if (nameInput === null) throw new Error("No #name input on the page");
nameInput.addEventListener("input", (event) => {
console.log(event.target.value);
});target-null.dom.ts:5:15 - error TS18047: 'event.target' is possibly 'null'.
target-null.dom.ts:5:28 - error TS2339: Property 'value' does not exist on type 'EventTarget'.
Two messages for one expression. TS18047 is Day 9’s “possibly null”. TS2339 says that even if the target is not null, an EventTarget has no value. Both are the checker speaking; nothing has run.
The fix is Day 16’s instanceof. target instanceof HTMLInputElement asks, while the program runs, whether the target really is an input box. Inside the if, the checker narrows it to HTMLInputElement, and null is ruled out too, because null is never an instance of anything.
Worked example: A live greeting
<label for="name">Your name</label>
<input id="name">
<p id="preview">Hello, stranger!</p>const nameInput = document.querySelector<HTMLInputElement>("#name");
const preview = document.querySelector<HTMLParagraphElement>("#preview");
if (nameInput === null || preview === null) {
throw new Error("The page is missing #name or #preview");
}
nameInput.addEventListener("input", (event) => {
const target = event.target;
if (target instanceof HTMLInputElement) {
preview.textContent = `Hello, ${target.value}!`;
}
});- Line 7: the
"input"event fires every time the text in the box changes, once per typed character. - Line 8:
targethas the typeEventTarget | null. - Line 9: the runtime check. If the target is an input box, the body runs; if not, nothing happens.
- Line 10: inside the
if,targetis anHTMLInputElement, so.value, the text currently in the box, is allowed. It is always a string.
Type Ana and the paragraph reads Hello, Ana!.
Here the check looks unnecessary: the listener is on nameInput, so of course the target is an input. But the checker reasons from types, not from what you know, and the type of event.target does not change with the element you attached to. The check is cheap, and it pays off as soon as one handler serves several elements:
<button id="small" type="button">Small</button>
<button id="medium" type="button">Medium</button>
<button id="large" type="button">Large</button>
<p id="choice">No size chosen.</p>const small = document.querySelector<HTMLButtonElement>("#small");
const medium = document.querySelector<HTMLButtonElement>("#medium");
const large = document.querySelector<HTMLButtonElement>("#large");
const choice = document.querySelector<HTMLParagraphElement>("#choice");
if (small === null || medium === null || large === null || choice === null) {
throw new Error("The page is missing an element");
}
const chooseSize = (event: MouseEvent): void => {
const target = event.target;
if (target instanceof HTMLButtonElement) {
choice.textContent = `You chose ${target.textContent}.`;
console.log(target.id);
}
};
small.addEventListener("click", chooseSize);
medium.addEventListener("click", chooseSize);
large.addEventListener("click", chooseSize);Click Large and then Small, and the console shows:
large
small
One function, chooseSize, is attached to all three buttons (lines 17–19), and the paragraph ends on You chose Small. The handler does not know or care which variable holds which button; it reads everything from event.target.
Watch out
Silencing the checker with as. (event.target as HTMLInputElement).value makes both messages go away. As Day 16 warned, as is a promise to the checker, not a check: nothing tests it while the program runs. If the target is some other element, .value gives undefined and the page shows the word “undefined” with no error to tell you why. Use instanceof, which really checks. Review question 18 shows this bug happening.
Key idea
event.target is the element the event happened to, typed EventTarget | null. Narrow it with if (event.target instanceof HTMLInputElement) (or whatever element you expect) before using its properties.
Pause and try
Question 3 · Debugging
The checker rejects line 5 of target-null.dom.ts (above) with TS18047 and TS2339. Rewrite the handler so it checks clean and prints what is in the box each time the text changes.
Check your reasoning
Narrow event.target with instanceof before reading value:
nameInput.addEventListener("input", (event) => {
if (event.target instanceof HTMLInputElement) {
console.log(event.target.value);
}
});The original read .value on a value typed EventTarget | null: TS18047 because it might be null, TS2339 because an EventTarget has no value. instanceof HTMLInputElement is a check that runs, and inside it the checker treats event.target as an HTMLInputElement, which has value. Writing nameInput.value instead would also work here, since there is only one box, but it does not carry over to a handler shared by several elements. (event.target as HTMLInputElement).value would also silence both messages, but it checks nothing.
Reread 19.3 Narrowing the Event Target if your fix differed.
Question 4 · Short answer
In sizes.dom.ts, why does if (target instanceof HTMLButtonElement) on line 11 let line 12 read target.textContent without an error, when event.target.textContent on its own would be rejected?
Check your reasoning
event.target is typed EventTarget | null: it might be null, and an EventTarget has no textContent. instanceof HTMLButtonElement checks, while the program runs, that the target really is a button. The checker understands that check, so inside the if it narrows target to HTMLButtonElement, which has textContent (and id), and it knows null cannot get past the check. A correct answer names the declared type, the runtime check, and the narrowing.
Reread 19.3 Narrowing the Event Target if your answer differed.
19.4 State and Render
As a page does more, handlers start to step on each other. Suppose a water tracker has a “Drink a cup” button and an “Undo” button. The text must say how many cups; “Drink” must turn off at the goal; “Undo” must turn off at zero. If each handler changes the text and the buttons by hand, each one must remember all three jobs, and the day one of them forgets, the page shows something that is no longer true.
The fix is a habit, not a new feature. Keep the facts in variables, and make one function draw the whole page from them:
- The state is the data the page is showing: here, the number of cups. It lives in ordinary variables at the top level of the script.
render()is a function you write that sets every part of the page that depends on the state, reading only from the state.- A handler does two things, in this order: change the state, then call
render().
So the page is always a picture of the state. Handlers never touch the page directly, and there is exactly one place to look when the page looks wrong.
Worked example: A water tracker
<p id="cups">0 of 8 cups</p>
<button id="drink" type="button">Drink a cup</button>
<button id="undo" type="button">Undo</button>const cupsText = document.querySelector<HTMLParagraphElement>("#cups");
const drinkButton = document.querySelector<HTMLButtonElement>("#drink");
const undoButton = document.querySelector<HTMLButtonElement>("#undo");
if (cupsText === null || drinkButton === null || undoButton === null) {
throw new Error("The page is missing an element");
}
const goal = 8;
let cups = 0;
const render = (): void => {
cupsText.textContent = `${cups} of ${goal} cups`;
drinkButton.disabled = cups === goal;
undoButton.disabled = cups === 0;
};
drinkButton.addEventListener("click", () => {
cups = cups + 1;
render();
});
undoButton.addEventListener("click", () => {
cups = cups - 1;
render();
});
render();- Lines 8–9: the state.
goalnever changes, so it is aconst;cupsdoes, so it is alet. - Lines 11–15:
rendersets the text and both buttons fromcups. A button’sdisabledproperty, whentrue, greys it out and stops it from being clicked or focused;cups === goalistrueexactly when there is nothing left to drink. - Lines 17–25: each handler changes
cupsby one and callsrender. - Line 27: one call to
renderas the page loads, so the page matches the state from the start. It disables Undo, becausecupsis 0.
Click Drink three times and Undo once:
| Event | cups after |
Text | Drink disabled | Undo disabled |
|---|---|---|---|---|
| Page loads | 0 | 0 of 8 cups |
false | true |
| Drink | 1 | 1 of 8 cups |
false | false |
| Drink | 2 | 2 of 8 cups |
false | false |
| Drink | 3 | 3 of 8 cups |
false | false |
| Undo | 2 | 2 of 8 cups |
false | false |
The page ends like this:
<p id="cups">2 of 8 cups</p>
<button id="drink" type="button">Drink a cup</button>
<button id="undo" type="button">Undo</button>The state does not have to be a number. Here it is an array of names, and render rebuilds a list from it, using Day 18’s way of rendering a list from an array:
<input id="guest">
<button id="add" type="button">Add guest</button>
<p id="count">0 guests</p>
<ul id="guests"></ul>const guestInput = document.querySelector<HTMLInputElement>("#guest");
const addButton = document.querySelector<HTMLButtonElement>("#add");
const count = document.querySelector<HTMLParagraphElement>("#count");
const list = document.querySelector<HTMLUListElement>("#guests");
if (
guestInput === null ||
addButton === null ||
count === null ||
list === null
) {
throw new Error("The page is missing an element");
}
const guests: string[] = [];
const render = (): void => {
count.textContent =
guests.length === 1 ? "1 guest" : `${guests.length} guests`;
list.textContent = "";
for (const guest of guests) {
const item = document.createElement("li");
item.textContent = guest;
list.append(item);
}
};
addButton.addEventListener("click", () => {
const name = guestInput.value.trim();
if (name === "") return;
guests.push(name);
guestInput.value = "";
render();
});
render();Type Ana and click Add guest, then type only spaces and click, then type Ben and click. The page ends with:
<p id="count">2 guests</p>
<ul id="guests">
<li>Ana</li>
<li>Ben</li>
</ul>
Line 19 empties the list by setting its text to "", which removes every child element, and lines 20 to 24 build it again from guests. Throwing the old items away and building new ones every time looks wasteful, but for a list of a few dozen items it is instant, and it means render never has to work out what changed. The click handler on lines 27 to 33 changes the state (push), clears the box, and calls render. The all-spaces attempt is turned away on line 29 before the state changes, so the count stays honest. guests is a const even though the list grows: const stops the variable from pointing at a different array, not the array from changing, as on Day 6.
Watch out
Changing the state and forgetting to render. This handler updates cups but never calls render:
const cupsText = document.querySelector<HTMLParagraphElement>("#cups");
const drinkButton = document.querySelector<HTMLButtonElement>("#drink");
if (cupsText === null || drinkButton === null) {
throw new Error("The page is missing an element");
}
let cups = 0;
const render = (): void => {
cupsText.textContent = `${cups} of 8 cups`;
};
drinkButton.addEventListener("click", () => {
cups = cups + 1;
console.log(`cups is now ${cups}`);
});
render();After two clicks the console shows:
cups is now 1
cups is now 2but the paragraph still reads 0 of 8 cups. Nothing is wrong with the state; the page is just not being redrawn. Neither the checker nor the browser can tell you, because forgetting to call a function is not an error. When a page does not update, first log the state, as line 15 does: if the state is right, the missing piece is a render() call. Add render(); after line 15.
Watch out
Writing render as a function declaration. It is natural to write function render() { … }, but on a page that uses narrowed elements, the checker objects:
const cupsText = document.querySelector<HTMLParagraphElement>("#cups");
if (cupsText === null) throw new Error("The page is missing #cups");
let cups = 0;
function render(): void {
cupsText.textContent = `${cups} of 8 cups`;
}
render();render-declaration.dom.ts:7:3 - error TS18047: 'cupsText' is possibly 'null'.Line 2 has already ruled out null, so why the complaint? A function declaration can be called from anywhere in the file, even from a line above the if on line 2, before the check has run. So the checker does not carry the narrowing into its body. A const holding an arrow function exists only from its own line onwards, below the check, so the narrowing does carry in. Write const render = (): void => { … };, as every example today does, and call it only after defining it. Undo this in main.ts once you have read the message.
Key idea
Keep the page’s data in variables (the state) and write one render() that draws everything from it. Every handler
changes the state and then calls render(), and the script calls render() once at the start.
Pause and try
Question 5 · Tracing
The user clicks Hit, Hit, Miss, Hit, Miss. Predict the paragraph’s text at the end.
<p id="score">Score: 0</p>
<button id="hit" type="button">Hit</button>
<button id="miss" type="button">Miss</button>const scoreText = document.querySelector<HTMLParagraphElement>("#score");
const hitButton = document.querySelector<HTMLButtonElement>("#hit");
const missButton = document.querySelector<HTMLButtonElement>("#miss");
if (scoreText === null || hitButton === null || missButton === null) {
throw new Error("The page is missing an element");
}
let score = 0;
let streak = 0;
const render = (): void => {
scoreText.textContent = `Score: ${score} (streak ${streak})`;
};
hitButton.addEventListener("click", () => {
streak = streak + 1;
score = score + streak;
render();
});
missButton.addEventListener("click", () => {
streak = 0;
});
render();Check your reasoning
Score: 4 (streak 1)
| Event | streak |
score |
render called? |
Paragraph |
|---|---|---|---|---|
| Page loads | 0 | 0 | yes (line 25) | Score: 0 (streak 0) |
| Hit | 1 | 1 | yes | Score: 1 (streak 1) |
| Hit | 2 | 3 | yes | Score: 3 (streak 2) |
| Miss | 0 | 3 | no | Score: 3 (streak 2) |
| Hit | 1 | 4 | yes | Score: 4 (streak 1) |
| Miss | 0 | 4 | no | Score: 4 (streak 1) |
The Miss handler changes streak but never calls render, so the page lags behind the state: after the last Miss, streak is 0 but the page still says 1. That is the forgotten-render bug; adding render(); to the Miss handler would make the final text Score: 4 (streak 0).
Reread 19.4 State and Render if your answer differed.
Question 6 · Short answer
A classmate’s water tracker has no render. The Drink handler does cups = cups + 1;, sets the text, and disables Drink at the goal. The Undo handler does cups = cups - 1; and sets the text. Describe a click sequence that leaves the page showing something false, and say how state-and-render prevents it.
Check your reasoning
Drink eight times: the text says 8 of 8 cups and Drink is disabled. Now click Undo: the text says 7 of 8 cups, but Drink stays disabled, because only the Drink handler ever changes drinkButton.disabled, and it is not the one that ran. The user can no longer drink even though they are below the goal. (Undo is also never disabled, so it can take cups below 0.)
With a render that sets the text and both buttons from cups, and every handler calling it, every part of the page is recalculated after every change, so no handler can forget a part. A correct answer names a sequence where one handler leaves another’s work stale, and says that one render reading only the state keeps everything in step.
Reread 19.4 State and Render if your answer differed.
19.5 Event Delegation
The guest list draws one <li> per guest. Suppose each guest needs a Remove button. You could attach a listener to every button inside render, but render builds new buttons every time it runs, so it would be attaching listeners again and again, and a page with 200 rows would hold 200 listeners. There is a simpler way, and it depends on how events travel.
When you click a button inside a list item inside a list, the click does not happen only to the button. The browser delivers the event to the button first, then to its parent <li>, then to the <ul>, then on up through every ancestor to document. This upward trip is called bubbling, like a bubble rising through water. ("click", "keydown", and "input" all bubble. That is how the key listener on document in 19.2 heard keys pressed inside the box.) At every stop, event.target is still the element that was actually clicked.
So one listener on the <ul> hears every click on every button inside it, including buttons that render creates later, and event.target says which one. Putting a single listener on a parent to handle events from its children is called event delegation: the children delegate their clicks to the parent.
Delegation needs one more piece. The handler knows which button was clicked, but which fruit does that button belong to? render writes the answer onto the button when it creates it, in a data attribute: an attribute whose name starts with data-, which HTML sets aside for your own information. Day 18’s setAttribute("data-id", fruit.id) stores it, and its partner getAttribute("data-id") reads it back. getAttribute gives string | null, null meaning the attribute is not there.
Worked example: Removing fruit with one listener
<ul id="fruits"></ul>
<p id="message"></p>type Fruit = { id: string; name: string };
const list = document.querySelector<HTMLUListElement>("#fruits");
const message = document.querySelector<HTMLParagraphElement>("#message");
if (list === null || message === null) {
throw new Error("The page is missing #fruits or #message");
}
let fruits: Fruit[] = [
{ id: "f1", name: "Apple" },
{ id: "f2", name: "Banana" },
{ id: "f3", name: "Cherry" },
];
const render = (): void => {
list.textContent = "";
for (const fruit of fruits) {
const item = document.createElement("li");
item.textContent = `${fruit.name} `;
const removeButton = document.createElement("button");
removeButton.type = "button";
removeButton.textContent = "Remove";
removeButton.setAttribute("data-id", fruit.id);
item.append(removeButton);
list.append(item);
}
};
list.addEventListener("click", (event) => {
const target = event.target;
if (!(target instanceof HTMLButtonElement)) {
console.log("Not a button, so nothing to do");
return;
}
const id = target.getAttribute("data-id");
const removed = fruits.find((fruit) => fruit.id === id);
fruits = fruits.filter((fruit) => fruit.id !== id);
message.textContent = `Removed ${removed?.name}`;
render();
});
render();- Lines 15–27:
renderbuilds one<li>per fruit, each holding the fruit’s name and a Remove button tagged withdata-id. - Line 29: the only listener, on the
<ul>. It is attached once, outsiderender, and the<ul>itself is never replaced, so the listener survives every redraw. - Line 31: anything that is not a button (the
<li>or the text beside the button) is turned away. - Line 35: inside,
targetis anHTMLButtonElement, andgetAttributereads its id: astring | null. - Lines 36–39: state first, then render.
findgrabs the fruit for the message,filterkeeps every fruit except that one, andrenderredraws. Comparing astringwith astring | nullusing===is fine; it is simplyfalsewhen the id isnull.
Click Banana’s Remove button, then the first list item’s text (not its button), then Apple’s Remove button. The console shows:
Not a button, so nothing to doand the page ends with:
<ul id="fruits">
<li>Cherry <button type="button" data-id="f3">Remove</button></li>
</ul>
<p id="message">Removed Apple</p>The second click shows why line 31 matters. Clicking the text of an item makes the <li> the target, and that click bubbles to the <ul> just like a button click does. Without the instanceof check, the handler would call getAttribute on an element with no data-id, find no fruit, and print Removed undefined. Narrowing the target is how a delegated handler picks out the clicks it cares about.
Key idea
Events bubble up from the element they happened to through all its ancestors. One listener on a parent therefore hears
its children’s events, including children render creates later; it narrows event.target to the kind of element it
handles and reads a data- attribute to know which item was meant.
Pause and try
Question 7 · Tracing
The user clicks Italic, then the <span>, then the empty space inside the <div> beside the buttons, then Bold. Predict the console.
<div id="toolbar">
<button id="bold" type="button">Bold</button>
<button id="italic" type="button">Italic</button>
<span id="hint">Pick a style</span>
</div>const toolbar = document.querySelector<HTMLDivElement>("#toolbar");
if (toolbar === null) throw new Error("The page is missing #toolbar");
toolbar.addEventListener("click", (event) => {
if (event.target instanceof HTMLButtonElement) {
console.log(`button ${event.target.id}`);
} else {
console.log("not a button");
}
});Check your reasoning
button italic
not a button
not a button
button boldAll four clicks bubble to the <div>, so the one listener runs four times. Each time, event.target is what was actually clicked: the Italic button (a button), the <span> (not a button), the <div> itself (not a button: a click on a parent’s own empty space makes the parent the target), and the Bold button. Inside the if, event.target is narrowed to HTMLButtonElement, so .id is allowed.
Reread 19.5 Event Delegation if your answer differed.
Question 8 · Multiple choice
In fruit-basket.dom.ts, render deletes every Remove button and makes new ones on every redraw. Why do the new buttons still work?
setAttribute("data-id", …)attaches a click listener to each new button- The listener is on the
<ul>, whichrendernever replaces, and clicks on the new buttons bubble up to it - The browser copies the old buttons’ listeners onto the new buttons
- They would not work; only the first set of buttons responds
Check your reasoning
B. The listener was attached once, to the <ul>. render only empties and refills the <ul>; it never replaces it. A click on any button inside it, old or new, bubbles up to the <ul>, and its listener reads event.target.
- A is wrong:
setAttributestores text on the element. It attaches nothing; thedata-idis only read later bygetAttribute. - C is wrong: a new element starts with no listeners, and nothing is copied. That is exactly why per-button listeners would have to be attached again inside
render. - D is wrong: the worked example removed two fruits in a row, the second from buttons made by a redraw.
Reread 19.5 Event Delegation if you chose differently.
19.6 Buttons, Not Clickable divs
Any element can have a click listener, including a plain <div>, and a <div> can be styled to look exactly like a button. It is tempting. But many people never click: they use the keyboard, pressing Tab to move from control to control and Enter or Space to press one, because they cannot use a mouse, because a screen reader is reading the page aloud to them, or because it is faster. Whether those people can use your page is called keyboard access (part of accessibility: making a page usable by everyone).
A real <button> gives keyboard access for free. It can receive focus, the state of being the element that key presses go to (the browser draws an outline around it); Tab moves focus to it; and when it has focus, Enter and Space press it, which fires the same "click" event a mouse would. A screen reader announces it as a button. A <div> does none of this: Tab skips it, so a keyboard user cannot reach it, and pressing Enter near it does nothing.
Worked example: Same handler, different element
<div id="fake" class="button-look">Save (div)</div>
<button id="real" type="button">Save (button)</button>
<p id="status"></p>const fake = document.querySelector<HTMLDivElement>("#fake");
const real = document.querySelector<HTMLButtonElement>("#real");
const status = document.querySelector<HTMLParagraphElement>("#status");
if (fake === null || real === null || status === null) {
throw new Error("The page is missing an element");
}
const save = (): void => {
status.textContent = "Saved!";
console.log("save ran");
};
fake.addEventListener("click", save);
real.addEventListener("click", save);
fake.focus();
console.log("div has focus:", document.activeElement === fake);
real.focus();
console.log("button has focus:", document.activeElement === real);Both elements get the same click handler, so with a mouse they behave the same. The difference is focus. An element’s focus() method moves focus to it, if it can take focus at all, and document.activeElement is the element that has focus now. As the page loads, the console shows:
div has focus: false
button has focus: truefake.focus() did nothing, because a <div> cannot take focus; real.focus() worked. Then send an Enter key press to the <div>: save does not run and the status paragraph stays empty. In a browser, pressing Tab until the button has its outline and then pressing Enter or Space shows Saved!; there is no way to do the same with the <div>.
You can bolt keyboard support onto a <div> (give it a tabindex attribute so it can take focus, a role attribute so screen readers call it a button, and a "keydown" listener for Enter and Space), but that is three things to remember and get right, and <button> already does all of them. Use the element that matches the job: <button> for anything that does something on the page, a link (<a href>) for anything that goes to another page. Give buttons type="button"; on Day 20 you will see that a button inside a form without it does something extra when pressed.
The same goes for delegated lists. In 19.5, the thing to click in each row was a <button> inside the <li>, not the <li> itself, so every row can be reached with Tab and pressed with Enter.
Key idea
Use <button type="button"> for anything clickable. It can take focus, Tab reaches it, Enter and Space press it with
the same "click" event as the mouse, and screen readers announce it. A clickable <div> gets none of this.
Pause and try
Question 9 · Multiple choice
A to-do page shows each task as <div class="task">Buy milk</div>, and one delegated "click" listener on the list toggles a task when its <div> is clicked. A user who only uses the keyboard opens the page. What happens?
- Everything works, because the listener handles
"click"and Enter counts as a click - Tab never reaches the tasks, so the user cannot toggle any of them
- Tab reaches the tasks, but Enter toggles two tasks at once because of bubbling
- The checker reports an error, because a
"click"listener needs a button
Check your reasoning
B. A <div> cannot take focus, so Tab skips it, and Enter only presses an element that has focus and is a button. The click listener never runs for this user.
- A is wrong because Enter becomes a
"click"only on elements such as<button>that take focus and act as buttons. - C is wrong because the user never reaches a task at all; bubbling is not the issue.
- D is wrong because any element may have a click listener, and the checker does not judge accessibility. This is a design bug that no tool reports.
The fix is a <button type="button"> inside each task row, as in 19.5’s fruit basket.
Reread 19.6 Buttons, Not Clickable divs if you chose differently.
19.7 Keyboard Shortcuts
Buttons make a page usable from the keyboard. Keyboard shortcuts go further: single keys that do common jobs without moving focus at all, like / to jump to a search box on many sites. You build them with one "keydown" listener on document and a check of event.key. Two details need care.
First, a key press bubbles from wherever focus is. If the user is typing a note in a text box and presses m, the "keydown" still reaches document, and a shortcut on m would fire in the middle of their sentence. So a shortcut handler checks event.target first and does nothing when the key was pressed inside an input box.
Second, many keys already do something. The arrow keys scroll the page; / may open the browser’s own quick search; a letter types itself into whatever has focus. This built-in behavior is the event’s default action, and event.preventDefault() tells the browser to skip it for this one event, so that only your code reacts. (Day 20 uses the same method for forms.) Call it only for keys you actually handle, or you would break typing and scrolling everywhere.
Worked example: Volume keys
<p id="volume">Volume: 5</p>
<label for="note">Note</label>
<input id="note">const volumeText = document.querySelector<HTMLParagraphElement>("#volume");
if (volumeText === null) throw new Error("The page is missing #volume");
let volume = 5;
const render = (): void => {
volumeText.textContent = volume === 0 ? "Volume: muted" : `Volume: ${volume}`;
};
document.addEventListener("keydown", (event) => {
if (event.target instanceof HTMLInputElement) return;
if (event.key === "ArrowUp") {
event.preventDefault();
volume = Math.min(volume + 1, 10);
} else if (event.key === "ArrowDown") {
event.preventDefault();
volume = Math.max(volume - 1, 0);
} else if (event.key === "m") {
volume = 0;
} else {
return;
}
console.log(`${event.key} -> ${volume}`);
render();
});
render();- Line 11: if the key was pressed inside an input box, leave it alone. Here
event.target instanceof HTMLInputElementis used for itstrueorfalse; nothing inside needs the narrowed type. - Lines 13–20: up and down change the state, with
Math.minandMath.maxkeeping it between 0 and 10, andpreventDefaultstops the page from scrolling.mmutes. - Lines 21–23: any other key returns before the log and the render.
- Lines 24–25: change made, so log it and render.
Press the up arrow twice, press m while typing in the Note box, press x, and press the down arrow. The console shows:
ArrowUp -> 6
ArrowUp -> 7
ArrowDown -> 6and the paragraph reads Volume: 6. The m in the Note box was ignored by line 11, so the volume was not muted; x was ignored by line 22.
A shortcut can also move focus, with the focus() method from 19.6. An input box takes focus, so search.focus() puts the typing cursor in it:
<label for="search">Search</label>
<input id="search">
<p>Press / to jump to the search box.</p>const search = document.querySelector<HTMLInputElement>("#search");
if (search === null) throw new Error("The page is missing #search");
document.addEventListener("keydown", (event) => {
if (event.key === "/" && event.target !== search) {
event.preventDefault();
search.focus();
}
console.log(
`after ${event.key}: search focused is ${document.activeElement === search}`,
);
});Press a, then /:
after a: search focused is false
after /: search focused is true
Line 5 checks two things: the key is /, and the key was not pressed inside the search box itself (comparing event.target with search using !== needs no narrowing). Without preventDefault on line 6, some browsers would also type the / into the box the moment it took focus, so the user’s search would start with a stray slash.
Key idea
A shortcut is a "keydown" listener on document that compares event.key with the key names it handles. Skip keys
pressed inside input boxes, and call event.preventDefault() only for the keys you handle, to stop the browser’s own
action for them.
Pause and try
Question 10 · Tracing
The user presses these keys, in order: c and a with nothing focused, x while typing in the box, Shift on its own, t, Backspace, and r. Predict the paragraph’s text.
<p id="letters"></p>
<input id="box">const letters = document.querySelector<HTMLParagraphElement>("#letters");
if (letters === null) throw new Error("The page is missing #letters");
let typed = "";
document.addEventListener("keydown", (event) => {
if (event.target instanceof HTMLInputElement) return;
if (event.key === "Backspace") {
typed = typed.slice(0, -1);
} else if (event.key.length === 1) {
typed = typed + event.key;
}
letters.textContent = typed;
});Check your reasoning
car
| Key | Line that decides | typed after |
|---|---|---|
| c | lines 10–11: one character | c |
| a | lines 10–11 | ca |
| x (box) | line 7: target is an input, return | ca |
| Shift | line 10: "Shift" has length 5 |
ca |
| t | lines 10–11 | cat |
| Backspace | lines 8–9: slice(0, -1) drops one |
ca |
| r | lines 10–11 | car |
The trap is Shift: its key is the name "Shift", not a character, so the length check on line 10 keeps it out. The x never reaches line 8, because the handler returns on line 7.
Reread 19.7 Keyboard Shortcuts and 19.2 Event Types if your answer differed.
19.8 Removing Listeners
A listener runs on every event until the page closes. Usually that is what you want, but not always: a guessing game should stop taking guesses when the tries run out, and the shortcuts for a pop-up panel should stop when the panel closes. removeEventListener(type, handler) undoes addEventListener: after it, that handler no longer runs for that event type on that element.
The rule that matters: you must pass the same function you added, the same function value, not one that looks the same. The browser keeps a list of the functions attached to each element and removes the one that is identical to what you pass. So a handler you plan to remove must be stored in a const, and that const is what you pass both times.
Worked example: Three tries
<button id="guess" type="button">Guess</button>
<p id="tries">3 tries left</p>const guessButton = document.querySelector<HTMLButtonElement>("#guess");
const triesText = document.querySelector<HTMLParagraphElement>("#tries");
if (guessButton === null || triesText === null) {
throw new Error("The page is missing #guess or #tries");
}
let triesLeft = 3;
const handleGuess = (): void => {
triesLeft = triesLeft - 1;
console.log(`Guess! ${triesLeft} left`);
if (triesLeft === 0) {
guessButton.removeEventListener("click", handleGuess);
triesText.textContent = "No tries left";
} else {
triesText.textContent = `${triesLeft} tries left`;
}
};
guessButton.addEventListener("click", handleGuess);The handler is in a const named handleGuess (line 9), attached on line 20, and removed on line 13, from inside itself, when the tries reach 0. Click Guess five times:
Guess! 2 left
Guess! 1 left
Guess! 0 leftThe fourth and fifth clicks print nothing: the button is still on the page, but nothing is listening to it. The paragraph reads No tries left. (Setting guessButton.disabled = true as well would tell the user the button is finished. Removing the listener stops the code; disabling shows it.)
When a handler should run only once, there is a shorter way. A third argument to addEventListener, the options object { once: true }, makes the browser remove the handler right after its first run, so you need no const and no removeEventListener:
const startButton = document.querySelector<HTMLButtonElement>("#start");
const status = document.querySelector<HTMLParagraphElement>("#status");
if (startButton === null || status === null) {
throw new Error("The page is missing #start or #status");
}
let starts = 0;
startButton.addEventListener(
"click",
() => {
starts = starts + 1;
status.textContent = `Started ${starts} time(s)`;
},
{ once: true },
);Click Start three times and the paragraph reads Started 1 time(s): only the first click ran the handler.
Watch out
Removing a function that was never added. Two arrow functions with the same text are still two different functions, just as two [] are two different arrays:
const ringButton = document.querySelector<HTMLButtonElement>("#ring");
if (ringButton === null) throw new Error("The page is missing #ring");
ringButton.addEventListener("click", () => {
console.log("Ding!");
});
ringButton.removeEventListener("click", () => {
console.log("Ding!");
});
console.log("Listener removed");Click Ring twice:
Listener removed
Ding!
Ding!Line 8 makes a brand-new function and asks to remove it. That function was never attached, so nothing is removed, and the browser says nothing about it. The checker cannot help either, because the code is well typed. Store the handler in a const and pass that const to both calls, as Question 11 asks.
Key idea
removeEventListener(type, handler) stops a handler, but only when handler is the same function value that was
added, so keep a handler you will remove in a const. For a handler that should run once, pass { once: true }.
Pause and try
Question 11 · Debugging
Fix remove-new-arrow.dom.ts so the clicks print nothing after Listener removed.
Check your reasoning
Store the handler once and pass the same const to both calls:
const ringButton = document.querySelector<HTMLButtonElement>("#ring");
if (ringButton === null) throw new Error("The page is missing #ring");
const ring = (): void => {
console.log("Ding!");
};
ringButton.addEventListener("click", ring);
ringButton.removeEventListener("click", ring);
console.log("Listener removed");Clicking Ring twice now leaves the console with only:
Listener removedIn the original, line 8 created a second arrow function. It looked like the first one, but it was a different function value, so removeEventListener found nothing to remove, and the first one kept running. With ring passed to both calls, the browser finds and removes exactly the function it stored.
Reread 19.8 Removing Listeners if your fix differed.
Question 12 · Multiple choice
A button has a handler added with { once: true } that adds 1 to count. The user clicks the button four times. What is count, if it started at 0?
- 0
- 1
- 4
- It depends on whether
removeEventListeneris also called
Check your reasoning
B. { once: true } makes the browser remove the handler right after its first run. The first click adds 1; the other three find nothing listening.
- A is wrong: the first click does run the handler; “once” means once, not never.
- C is wrong: that is what happens without the option.
- D is wrong: no
removeEventListeneris needed, because the option does the removal itself.
Reread 19.8 Removing Listeners if you chose differently.
Putting it together
A theater’s seat picker shows each seat as a button. Free seats can be picked and unpicked by clicking; taken seats cannot be clicked; Escape clears every pick; and Confirm books the picked seats and locks the picker so nothing can change afterwards. Every idea from today appears in it.
<div id="seats"></div>
<p id="summary"></p>
<button id="confirm" type="button">Confirm seats</button>type SeatStatus = "free" | "taken" | "picked";
type Seat = { id: string; status: SeatStatus };
const seatGrid = document.querySelector<HTMLDivElement>("#seats");
const summary = document.querySelector<HTMLParagraphElement>("#summary");
const confirmButton = document.querySelector<HTMLButtonElement>("#confirm");
if (seatGrid === null || summary === null || confirmButton === null) {
throw new Error("The page is missing an element");
}
let seats: Seat[] = [
{ id: "A1", status: "taken" },
{ id: "A2", status: "free" },
{ id: "A3", status: "free" },
{ id: "B1", status: "free" },
{ id: "B2", status: "free" },
];
let confirmed = false;
const pickedIds = (): string[] =>
seats.filter((seat) => seat.status === "picked").map((seat) => seat.id);
const render = (): void => {
seatGrid.textContent = "";
for (const seat of seats) {
const button = document.createElement("button");
button.type = "button";
button.textContent = seat.id;
button.setAttribute("data-id", seat.id);
button.setAttribute("aria-pressed", String(seat.status === "picked"));
button.classList.add(seat.status);
button.disabled = seat.status === "taken" || confirmed;
seatGrid.append(button);
}
const ids = pickedIds();
if (confirmed) {
summary.textContent = `Booked: ${ids.join(", ")}`;
} else if (ids.length === 0) {
summary.textContent = "No seats picked";
} else {
summary.textContent = `Picked: ${ids.join(", ")}`;
}
confirmButton.disabled = confirmed || ids.length === 0;
};
const handleSeatClick = (event: MouseEvent): void => {
if (!(event.target instanceof HTMLButtonElement)) return;
const id = event.target.getAttribute("data-id");
seats = seats.map((seat) => {
if (seat.id !== id || seat.status === "taken") return seat;
return {
id: seat.id,
status: seat.status === "picked" ? "free" : "picked",
};
});
render();
};
const handleKey = (event: KeyboardEvent): void => {
if (event.key !== "Escape") return;
seats = seats.map((seat) =>
seat.status === "picked" ? { id: seat.id, status: "free" } : seat,
);
render();
};
seatGrid.addEventListener("click", handleSeatClick);
document.addEventListener("keydown", handleKey);
confirmButton.addEventListener("click", () => {
confirmed = true;
seatGrid.removeEventListener("click", handleSeatClick);
document.removeEventListener("keydown", handleKey);
console.log(`Booked ${pickedIds().length} seats`);
render();
});
render();| Lines | What happens | Idea |
|---|---|---|
| 1–2 | Each seat’s status is a literal union, so a typo such as "pikced" is a type error |
Day 9 |
| 11–18 | The state: the seats and whether the booking is confirmed | 19.4 |
| 23–44 | render draws every seat, the summary, and the Confirm button from the state alone |
19.4 |
| 26–33 | Each seat is a real <button> with a data-id; aria-pressed tells screen readers whether a seat is picked; taken seats are disabled |
19.5, 19.6 |
| 46–57 | One delegated handler on the grid, stored in a const and typed with MouseEvent; it narrows the target, reads the id, and maps the state to a new array |
19.2, 19.3, 19.5 |
| 59–65 | A KeyboardEvent handler: Escape turns every picked seat back to free |
19.7 |
| 70–76 | Confirm changes the state, then removes both handlers, which is why they had to be stored in consts |
19.8 |
| 78 | The first render, as the page loads | 19.4 |
Click A2 and B1, press Escape, click the taken seat A1, click A3 and B2, click Confirm, and press Escape again. The console shows:
Booked 2 seats
and the page ends like this:
<div id="seats">
<button type="button" data-id="A1" aria-pressed="false" class="taken" disabled="">A1</button>
<button type="button" data-id="A2" aria-pressed="false" class="free" disabled="">A2</button>
<button type="button" data-id="A3" aria-pressed="true" class="picked" disabled="">A3</button>
<button type="button" data-id="B1" aria-pressed="false" class="free" disabled="">B1</button>
<button type="button" data-id="B2" aria-pressed="true" class="picked" disabled="">B2</button>
</div>
<p id="summary">Booked: A3, B2</p>
<button id="confirm" type="button" disabled="">Confirm seats</button>
Follow the clicks: A2 and B1 become picked; Escape frees them both; the click on A1 does nothing, because a disabled button fires no click at all; A3 and B2 become picked; Confirm sets confirmed, removes both listeners, and renders, which disables every seat. The last Escape changes nothing, because handleKey is no longer attached. The class on each button (free, taken, picked) is there so a stylesheet can color the seats. To see it, add <style>.picked { background: gold; }</style> inside the <head> of index.html.
Vocabulary
| Term | Definition | Example |
|---|---|---|
| event | The browser’s report that something happened to an element, such as a click or a key press | a click on #ring |
| event listener | A request to the browser to call a function each time an event of a type happens to an element | button.addEventListener("click", ring) |
| event handler | The function the browser calls for each event | () => { rings = rings + 1; } |
| overload | One of several parameter lists a function accepts; the checker reports each one that failed | addEventListener’s two forms |
| event type | The string naming which event to listen for | "click", "keydown", "input" |
| event object | The argument passed to a handler, describing the event | event.key, event.target |
Event |
The general event object type: type and target |
the parameter of an "input" handler |
MouseEvent |
An event object with pointer details; a click gives a PointerEvent, a kind of MouseEvent |
(event: MouseEvent): void => { … } |
KeyboardEvent |
An event object with key, the key pressed |
event.key === "Escape" |
EventTarget |
Anything that can receive events; event.target is EventTarget | null |
narrowed with instanceof HTMLInputElement |
disabled |
A button property that, when true, stops the button being clicked or focused |
undoButton.disabled = cups === 0; |
| state | The data a page shows, kept in variables | let cups = 0; |
| render | A function that sets every part of the page from the state | const render = (): void => { … }; |
| bubbling | An event’s trip from its target up through every ancestor | a button click reaching the <ul> |
| event delegation | One listener on a parent handling events from its children | list.addEventListener("click", …) |
| data attribute | An attribute starting with data- that holds your own information |
data-id="f2", read with getAttribute |
| focus | Being the element that key presses go to | search.focus(), document.activeElement |
| keyboard access | Every control can be reached with Tab and used with Enter or Space | a <button>, not a clickable <div> |
| default action | What the browser does on its own for an event | an arrow key scrolling the page |
preventDefault() |
Tells the browser to skip the default action for this event | event.preventDefault(); |
removeEventListener |
Stops a handler; needs the same function value that was added | button.removeEventListener("click", ring) |
Summary
addEventListener(type, handler)makes the browser callhandlereach time that event happens; attaching runs nothing. The event type decides the handler’s parameter: aPointerEvent(a kind ofMouseEvent) for"click", aKeyboardEventfor"keydown", anEventfor"input".event.targetis typedEventTarget | null; narrow it withinstanceofbefore readingvalueortextContent, and avoidas, which checks nothing.- Keep the data in variables (the state), draw the whole page from it in one
render(), and have every handler change the state and then callrender(). - Events bubble up to every ancestor, so one listener on a parent (event delegation) handles clicks on all its children, even ones
rendercreates later; adata-attribute says which item was clicked. - Use
<button type="button">for anything clickable so keyboard users can reach and press it; keyboard shortcuts skip keys typed in input boxes and callpreventDefault()only for keys they handle.removeEventListenerneeds the same function that was added, and{ once: true }removes a handler after its first run.
Practice
Do these in your day19 project, with npm run dev running. First make sure npx tsc prints nothing: if you typed wrong-event.dom.ts, target-null.dom.ts, render-declaration.dom.ts, or called-handler.dom.ts into main.ts, fix or undo it. For each exercise, write the page in index.html and the script in src/main.ts yourself, check it with npx tsc, try it in the browser with both the mouse and the keyboard (Tab, Enter, Space), and only then open the answer.
Question 13 · Short answer
Counter. Build a counter with increment, decrement, and reset buttons. Keep the count in a state variable, draw it with render(), and disable Reset when the count is already 0.
Check your reasoning
One possible solution:
<p id="count">0</p>
<button id="decrement" type="button">−1</button>
<button id="increment" type="button">+1</button>
<button id="reset" type="button">Reset</button>const countText = document.querySelector<HTMLParagraphElement>("#count");
const decrementButton = document.querySelector<HTMLButtonElement>("#decrement");
const incrementButton = document.querySelector<HTMLButtonElement>("#increment");
const resetButton = document.querySelector<HTMLButtonElement>("#reset");
if (
countText === null ||
decrementButton === null ||
incrementButton === null ||
resetButton === null
) {
throw new Error("The page is missing an element");
}
let count = 0;
const render = (): void => {
countText.textContent = String(count);
resetButton.disabled = count === 0;
};
incrementButton.addEventListener("click", () => {
count = count + 1;
render();
});
decrementButton.addEventListener("click", () => {
count = count - 1;
render();
});
resetButton.addEventListener("click", () => {
count = 0;
render();
});
render();Click +1 three times, −1 once, Reset, and −1 once, and the count reads -1. The state is count (line 14). render (lines 16–19) sets the number and Reset’s disabled from it, and each of the three handlers changes count and calls render. The first render() on line 36 disables Reset at the start. String(count) turns the number into text for textContent. Try adding a rule that disables −1 at 0 instead of allowing negatives: it is one more line in render, and no handler changes.
Reread 19.4 State and Render if your result differed.
Question 14 · Short answer
Toggle tasks. Render an array of tasks as a list. Clicking a task toggles it between done and not done, using one delegated listener on the list. Show how many tasks are done.
Check your reasoning
One possible solution:
<ul id="tasks"></ul>
<p id="progress"></p>type Task = { id: string; title: string; done: boolean };
const list = document.querySelector<HTMLUListElement>("#tasks");
const progress = document.querySelector<HTMLParagraphElement>("#progress");
if (list === null || progress === null) {
throw new Error("The page is missing #tasks or #progress");
}
let tasks: Task[] = [
{ id: "t1", title: "Buy milk", done: false },
{ id: "t2", title: "Walk the dog", done: false },
{ id: "t3", title: "Read Day 19", done: false },
];
const render = (): void => {
list.textContent = "";
for (const task of tasks) {
const item = document.createElement("li");
const button = document.createElement("button");
button.type = "button";
button.textContent = task.title;
button.setAttribute("data-id", task.id);
button.setAttribute("aria-pressed", String(task.done));
if (task.done) button.classList.add("done");
item.append(button);
list.append(item);
}
const doneCount = tasks.filter((task) => task.done).length;
progress.textContent = `${doneCount} of ${tasks.length} done`;
};
list.addEventListener("click", (event) => {
if (!(event.target instanceof HTMLButtonElement)) return;
const id = event.target.getAttribute("data-id");
tasks = tasks.map((task) =>
task.id === id
? { id: task.id, title: task.title, done: !task.done }
: task,
);
render();
});
render();Click Buy milk, Read Day 19, Buy milk again, and the empty space of the list, and the page ends with:
<ul id="tasks">
<li><button type="button" data-id="t1" aria-pressed="false">Buy milk</button></li>
<li><button type="button" data-id="t2" aria-pressed="false">Walk the dog</button></li>
<li><button type="button" data-id="t3" aria-pressed="true" class="done">Read Day 19</button></li>
</ul>
<p id="progress">1 of 3 done</p>Each task is a <button> inside its <li>, so it can be reached with Tab and toggled with Enter or Space. aria-pressed tells a screen reader whether it is done, and the done class lets a stylesheet strike it through. The one listener on line 32 turns away clicks that are not on a button, reads the id, and uses map to build a new array in which only that task’s done is flipped; render then redraws the list and the count. Buy milk was clicked twice, so it is back to not done.
Reread 19.5 Event Delegation if your result differed.
Question 15 · Short answer
Keyboard shortcuts. Add a “new task” input to a page. Pressing n anywhere outside an input box moves focus to it (without typing an n into it); pressing Escape while in it empties it and moves focus out.
Check your reasoning
One possible solution:
<label for="new-task">New task</label>
<input id="new-task">
<p>Press n to add a task, Escape to clear the box.</p>const newTask = document.querySelector<HTMLInputElement>("#new-task");
if (newTask === null) throw new Error("The page is missing #new-task");
document.addEventListener("keydown", (event) => {
const typing = event.target instanceof HTMLInputElement;
if (event.key === "n" && !typing) {
event.preventDefault();
newTask.focus();
} else if (event.key === "Escape" && event.target === newTask) {
newTask.value = "";
newTask.blur();
}
console.log(
`${event.key}: box focused ${document.activeElement === newTask}, value "${newTask.value}"`,
);
});Press n, type Water the plants, press n again inside the box, press Escape, and press Escape once more outside it. The console shows:
n: box focused true, value ""
n: box focused true, value "Water the plants"
Escape: box focused false, value ""
Escape: box focused false, value ""Line 5 works out whether the key was pressed inside an input box. The first n was not, so line 8 stops the browser typing the letter and line 9 moves focus to the box. The second n was typed inside the box, so it is just a letter (in a browser it would appear in the text). Escape inside the box empties it and calls blur(), the opposite of focus(), which takes focus away. The last Escape was not in the box, so nothing changes. Day 20 turns this box into a form that adds the task to the list.
Reread 19.7 Keyboard Shortcuts if your result differed.
Review questions
Question 16 · Tracing
The user clicks Add a star twice. Predict the console and the paragraph’s text, then say what is wrong with this code.
<button id="add" type="button">Add a star</button>
<p id="stars"></p>const addButton = document.querySelector<HTMLButtonElement>("#add");
const starsText = document.querySelector<HTMLParagraphElement>("#stars");
if (addButton === null || starsText === null) {
throw new Error("The page is missing #add or #stars");
}
let stars = 0;
const render = (): void => {
starsText.textContent = "*".repeat(stars);
addButton.addEventListener("click", () => {
stars = stars + 1;
console.log(`stars is ${stars}`);
render();
});
};
render();Check your reasoning
stars is 1
stars is 2
stars is 3The paragraph reads ***: three stars after two clicks.
| Event | Listeners on #add when it starts |
What happens |
|---|---|---|
| Page loads | 0 | render() attaches listener 1 |
| First click | 1 | Listener 1: stars is 1, render attaches listener 2 |
| Second click | 2 | Listener 1: stars is 2, attaches listener 3; listener 2: stars is 3, attaches listener 4 |
A listener added while an event is being handled does not run for that same event, which is why the first click printed only one line. The bug is line 11: render attaches a new listener every time it runs, so each render adds one more, and each click runs all of them. render should only draw. Attach listeners once, outside render, as every example in this guide does; the next click here would add 4 stars.
Reread 19.4 State and Render and 19.1 Listening for Events if your answer differed.
Question 17 · Multiple choice
On the water tracker in 19.4, which change would break keyboard access?
- Replacing
drinkButton.disabled = cups === goal;with nothing, so Drink can always be clicked - Replacing the Drink
<button>with a<div id="drink">styled to look the same, and keeping the same"click"listener - Attaching the Drink handler with
{ once: true } - Listening for
"click"ondocumentand checkingevent.targetwithinstanceof HTMLButtonElementinstead
Check your reasoning
B. A <div> cannot take focus, so Tab never reaches it and Enter or Space cannot press it. Mouse users would notice nothing; keyboard users could not drink at all. (The script would also need querySelector<HTMLDivElement>, since the element is no longer a button.)
- A is wrong: that is a state bug (cups could go past the goal), but the button is still reachable and pressable from the keyboard.
- C is wrong: that breaks Drink for everyone after one press, mouse and keyboard alike. It is not about the keyboard.
- D is wrong: that is event delegation. Keyboard presses on a focused button still fire
"click", which bubbles todocument, so keyboard users are fine.
Reread 19.6 Buttons, Not Clickable divs if you chose differently.
Question 18 · Debugging
This page should say which color was picked. npx tsc is happy, but clicking Red shows You picked undefined. Find the bug and fix it.
<p id="colors">
<span>Red</span>
<span>Green</span>
</p>
<p id="picked"></p>const colors = document.querySelector<HTMLParagraphElement>("#colors");
const picked = document.querySelector<HTMLParagraphElement>("#picked");
if (colors === null || picked === null) {
throw new Error("The page is missing #colors or #picked");
}
colors.addEventListener("click", (event) => {
const choice = (event.target as HTMLInputElement).value;
picked.textContent = `You picked ${choice}`;
});Check your reasoning
Line 8 uses as to tell the checker the target is an input box. It is not: the click was on a <span>, and a <span> has no value, so reading it gives undefined. as checks nothing while the program runs, so there is no error, only a wrong page. Replace the assertion with an instanceof check for the element that is really there, and read its text:
const colors = document.querySelector<HTMLParagraphElement>("#colors");
const picked = document.querySelector<HTMLParagraphElement>("#picked");
if (colors === null || picked === null) {
throw new Error("The page is missing #colors or #picked");
}
colors.addEventListener("click", (event) => {
if (event.target instanceof HTMLSpanElement) {
picked.textContent = `You picked ${event.target.textContent}`;
}
});Clicking Red now shows You picked Red. Clicking the space between the two spans makes the <p> the target, which fails the check, so nothing changes, instead of showing undefined. This is delegation (19.5) with the narrowing done properly (19.3).
Reread 19.3 Narrowing the Event Target if your fix differed.
Question 19 · Short answer
In the seat picker (Putting it together), handleSeatClick and handleKey are stored in consts, while the Confirm handler is written inline. Explain why the first two must be named, and what would go wrong if handleKey were written inline inside document.addEventListener("keydown", …) instead.
Check your reasoning
Confirm removes the seat and key handlers with removeEventListener, which only removes a function if it is the very same function value that was added. Storing each in a const lets the same value be passed to both addEventListener and removeEventListener. If handleKey were written inline, there would be no way to name that function later; any arrow passed to removeEventListener would be a new function, nothing would be removed, and Escape would still free picked seats after the booking was confirmed (and render would then show the booking as changed). The Confirm handler is never removed, so it can be inline. A correct answer names “same function value” and the Escape-after-Confirm symptom.
Reread 19.8 Removing Listeners if your answer differed.
Question 20 · Multiple choice
On the volume page in 19.7, a student deletes line 11 (if (event.target instanceof HTMLInputElement) return;). The volume is 5. They click in the Note box and type my song. What happens?
- Nothing different: the listener is on
document, so keys typed in the box never reach it - The
mmutes the volume, and the rest of the letters are ignored - The checker rejects the program, because
event.targetis no longer narrowed - Every letter typed changes the volume
Check your reasoning
B. Key presses bubble from the box up to document, so the listener hears all of them. With line 11 gone, nothing checks where the key came from:
const volumeText = document.querySelector<HTMLParagraphElement>("#volume");
if (volumeText === null) throw new Error("The page is missing #volume");
let volume = 5;
const render = (): void => {
volumeText.textContent = volume === 0 ? "Volume: muted" : `Volume: ${volume}`;
};
document.addEventListener("keydown", (event) => {
if (event.key === "ArrowUp") {
event.preventDefault();
volume = Math.min(volume + 1, 10);
} else if (event.key === "ArrowDown") {
event.preventDefault();
volume = Math.max(volume - 1, 0);
} else if (event.key === "m") {
volume = 0;
} else {
return;
}
console.log(`${event.key} -> ${volume}`);
render();
});
render();Pressing m and then y inside the Note box prints:
m -> 0and the paragraph reads Volume: muted. The m in “my” matched line 17; the y fell through to the else and returned before the log. The other letters of “my song” fall through the same way, so the volume stays muted.
- A is wrong:
"keydown"bubbles, which is exactly why line 11 was needed. - C is wrong: the rest of the handler only reads
event.key, which everyKeyboardEventhas, so nothing needed the narrowing. - D is wrong: only the arrow keys and
mare handled; every other key returns at line 20 of the edited file.
Reread 19.7 Keyboard Shortcuts and 19.5 Event Delegation if you chose differently.
Go further
MDN’s two guides explain events from the browser’s side, including the parts of bubbling this course skipped: MDN: Introduction to events and MDN: Event bubbling, whose last part is about event delegation.
Reflection
- I can attach a handler with addEventListener and explain why its body runs later, once per event. Reread
- I can say which event type the checker gives a click, keydown, or input handler, and annotate a separate handler. Reread
- I can narrow event.target with instanceof before reading its properties, and say why as is not a fix. Reread
- I can keep a page in state variables and redraw it with one render() after every change. Reread
- I can handle clicks on a whole list with one delegated listener and a data- attribute. Reread
- I can explain why a button works from the keyboard and a clickable div does not. Reread
- I can write a keyboard shortcut that ignores keys typed in input boxes and uses preventDefault only when needed. Reread
- I can remove a listener with the same function I added, or use once: true. Reread