The shop window that purrs
addEventListener, the event object, state and re-rendering, bubbling, preventDefault.
An event is the browser saying "something happened": a click (click), typing in a field (input), a key press (keydown), a form being sent (submit). You subscribe with addEventListener(type, handler): "when a click happens, call this function". The handler is an ordinary callback: we hand it to the browser, and the browser calls it when the time comes.
const button = document.querySelector("#meow");
const counter = document.querySelector("#count");
let purrs = 0;
function onClick() {
purrs += 1;
counter.textContent = purrs;
console.log("Purr #" + purrs);
}
button.addEventListener("click", onClick);
button.click();
button.click();button.click() is a click made by code. Make the rest yourself on the page tab.The browser doesn't call a handler empty-handed: the first argument is the event object. It holds everything about what happened:
event.type: the kind,"click","input"…;- event.target: the element where it happened (what was clicked, where someone types);
- event.currentTarget: the element this handler is attached to;
- event.key: which key was pressed (for
keydown):"Enter","Escape","a".
const input = document.querySelector("#name");
const echo = document.querySelector("#echo");
input.addEventListener("input", (event) => {
echo.textContent = "Toy: " + event.target.value;
});
input.addEventListener("keydown", (event) => {
console.log("Key:", event.key);
if (event.key === "Enter") console.log("Saving \"" + input.value + "\"");
});
// Pretend to be a customer, just like the tests do
input.value = "Mouse";
input.dispatchEvent(new Event("input"));
input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter" }));input fires on every character, keydown on every key. dispatchEvent fires an event from code.How do you build an interactive page without getting lost? One simple rule: data lives in variables, the page is a reflection of it. A handler doesn't patch the screen by eye. It does two things: 1) changes the data; 2) calls render(), which redraws the page from the data. That way the page never disagrees with what the program knows.
let favorite = false;
const button = document.querySelector("#fav");
const note = document.querySelector("#note");
function render() {
button.textContent = favorite ? "★ Saved" : "☆ Save";
note.textContent = favorite ? "Byte wants this mouse!" : "Byte is not impressed yet.";
}
button.addEventListener("click", () => {
favorite = !favorite; // 1. change the data
render(); // 2. redraw the page
});
button.click();
console.log(button.textContent);favorite. Everything on screen is derived from it.Now the trick. You click an icon inside a button, and the button sits inside a list. Who gets the click? All of them, in turn. The event happens on the deepest element and then bubbles up: icon → button → list item → list → … → document. So you can put one handler on the whole list and find out exactly what was clicked. This is called event delegation.
const list = document.querySelector("#toys");
list.addEventListener("click", (event) => {
const button = event.target.closest("button");
if (!button) return; // clicked between the buttons
console.log("Clicked", event.target.tagName, "→ button", button.dataset.toy);
});
list.querySelector("b").click(); // the icon inside the first button
list.querySelectorAll("button")[2].click();event.target is where the click landed (maybe a <b>). closest("button") climbs from there to the nearest button.Some events come with a default action: a link takes you to another page, a form submits and reloads the page. event.preventDefault() tells the browser "thanks, I've got this". And removeEventListener(type, the same function) takes a handler off, for example when a gift can be claimed only once.
const link = document.querySelector("#cart");
link.addEventListener("click", (event) => {
event.preventDefault(); // the browser stays on this page
console.log("Opening the cart without a reload");
});
link.click();
const gift = document.querySelector("#gift");
function takeGift() {
console.log("Gift claimed!");
gift.removeEventListener("click", takeGift);
}
gift.addEventListener("click", takeGift);
gift.click();
gift.click();this. In a function handler, this is the element the handler is attached to, the same as event.currentTarget. An arrow has no this of its own and takes it from outside (remember the classes chapter?). I don't guess: I write event.currentTarget, which is clear in any kind of function.Pop quiz
Mistakes are fine: keep trying until you find the right answer, and Byte explains why it's right.