Events and handlers
You'll learn how a page reacts to a click: you hand the browser a function, and it calls that function each time the event happens.
Watch & read
Start with the required ones. The others are there when you need them.
See it step by step
Set up a handler, then watch each click run it.
Explanation
Most code you've seen runs from top to bottom and then stops. But an app has to wait. It can't know when you'll tap "Send money". It needs a way to say: when this happens, run that.
Something that happens on the page, like a click, a key press or a form being sent, is called an event. The function you want to run is called an event handler.
Think of a doorbell. You don't stand at the door all day. You fix a bell, and when someone presses it, the bell rings and you go. Setting up the handler is fixing the bell. The click is someone pressing it.
const button = document.querySelector("button");let score = 0;button.addEventListener("click", () => {score = score + 1;console.log("Score:", score);});
addEventListener takes two things: the event name ("click") and a function. The browser keeps that
function and calls it later, once for every click. A function you hand over to be called later is a
callback. Nothing inside it runs when the page loads. Only the setup runs.
The browser also passes your handler an event object with details about what happened:
(event) => console.log(event.type) prints click. For a text box, event.target.value is what the
person typed.
People often write addEventListener("click", addOne()). The brackets call addOne right now,
once, and hand over its result (undefined) instead of the function. Pass the name with no brackets:
addEventListener("click", addOne). Or wrap it in an arrow: () => addOne().
In React you'll write the same idea as <button onClick={addOne}>. Same rule, same mistake.
When you read event code, find three things: which element, which event, and which function runs. Then remember that function's body runs later, not now.
Code tour
Click a line number with a ring to read the note for that line.
Practice
Short drills. Take your time and read the code before you answer.
1let count = 0;2function addOne() {3 count = count + 1;4 console.log("clicked", count);5}6button.addEventListener("click", addOne);7console.log("ready", count);8// Now the user clicks the button twice.
taps should stay 0 until the button is clicked, then go up by one on each click. Here button is a plain event target, and the checks click it for you. Fix the code so both checks pass.Quick check
3 questions. Each one explains itself after you answer.
- 1 / 3
button.addEventListener("click", () => console.log("Paid"));When isPaidprinted? - 2 / 3Which line runs
addOneon every click? - 3 / 3In
input.addEventListener("input", (event) => ...), where is the text the person typed?
Explain it back
How confident are you with Events and handlers?
Done
addEventListener or onClick code and say which function runs, and when.