JavaScript course · Part 4: The page · lab 5 of 11
Events: making the page respond
Listening for what people do, handling a form without reloading the page, one listener for a whole list, and keyboard support that is not an afterthought.
By the end you can
- Listen for an event and use what it tells you
- Handle a form submission and show a useful message
- Use one listener for many items, including ones added later
- Make your controls work for someone using a keyboard
Easier if you did first
step 1 of 4
Listening for what people do
A web page spends almost all its time waiting. Someone clicks, types, scrolls or submits, and your code runs in response. Those moments are called events.
You listen with addEventListener, which takes the name of the event and a function to run: button.addEventListener("click", handleClick).
Notice what is passed: the function itself, not a call to it. handleClick without brackets means 'here is the function'. handleClick() means 'run it now and give me the result', which runs it immediately, once, and listens for nothing.
Your function is handed an event object describing what happened. The useful part is event.target, the element it happened on.
Two older ways exist. The onclick attribute in HTML mixes behaviour into your markup and allows only one handler. Setting element.onclick in code allows only one as well, so a second one silently replaces the first. addEventListener allows as many as you like and is what to use.
Make the button on the right count its own clicks.
const button = document.querySelector("#save");
button.addEventListener("click", (event) => {
console.log("clicked", event.target);
});
addEventListener("click", handler) the function itself
addEventListener("click", handler()) runs it now. Wrong.What these words mean
- event
- Something that happened: a click, a key press, a form submission.
- addEventListener
- Run this function whenever that event happens here.
- event object
- The details, handed to your function.
- event.target
- The element the event happened on.
- handler
- The function you give to addEventListener.
Easy to get wrong
button.addEventListener("click", handleClick())
button.addEventListener("click", handleClick)
With brackets you run the function immediately and hand its result to the listener, so it fires once on load and never again when clicked.
element.onclick = handler, twice
addEventListener, twice
The second assignment replaces the first with no warning, so one of your two features quietly stops working.
What we check
- You listened for a click
- Two clicks show 2
- The button's own text is what changes
- You used addEventListener, not onclick