Events
- Event listeners
- Reading input values
Every script you've written so far runs once, the instant the page loads, and then goes quiet. Real interactivity waits — for a click, a tap, a keystroke — and reacts only when it happens.
addEventListener: wiring a switch to an action
let powerButton = document.querySelector("#power-button");
powerButton.addEventListener("click", function () {
document.body.classList.toggle("dark");
});.addEventListener(...) takes two things: the event type you're
listening for — "click" is the most common — and a function to run
when it happens. That function is built exactly like lesson 3's, just
handed over instead of called yourself: you never write
powerButton(); the browser calls it for you, the instant someone
clicks.
Nothing inside that function runs at page load. It sits wired and ready, however long it takes for the click to actually happen.
Reading what someone typed
A text box's typed content lives in its .value property — not
textContent, which is for an element's visible content, not an
input's current text:
let nameInput = document.querySelector("#name-input");
let typedName = nameInput.value;Put the two together — a listener that reads a value the moment it fires — and you've got a page that responds to a real person:
let button = document.querySelector("#greet-button");
button.addEventListener("click", function () {
let name = document.querySelector("#name-input").value;
document.querySelector("#greeting").textContent = "Hello, " + name + "!";
});Common mistake
Read .value too early — outside the listener, right when the page
loads — and you capture whatever was typed (usually nothing) at that
instant, frozen, forever. .value only reflects what's actually in the
box right now if you read it from inside the function that runs on
the click — the whole reason the reading has to happen inside the
listener, not once up front.
What comes next
You've now got every piece: values, decisions, loops, DOM access, and a reason for any of it to run — a real event. The project ahead uses every one of them on a page you already know: your own About Me page, wired up at last.
One greeting button in the lab first.