Show contents
Chapter 4 of 6 · 20 min
Events: reacting to the user
By the end of this chapter, you'll be able to
- React to an event with addEventListener
- Use the event object: target, preventDefault
- Handle a form in JavaScript without reloading the page
- Manage many elements with a single listener thanks to delegation
Listening to an event
element.addEventListener(type, function) asks the browser to call a function every time an event happens on the element:
const button = document.querySelector("#plus");
const display = document.querySelector("#total");
let total = 0;
button.addEventListener("click", () => {
total += 1;
display.textContent = total;
});
The most useful events:
| Event | When? |
|---|---|
click | a click, or the Enter or Space key on a button |
input | on every change to a field |
change | when a choice is confirmed (list, checkbox) |
submit | a form is submitted |
keydown | a key is pressed |
On a <button>, the click event also fires with the keyboard: a real button is accessible without any effort. That's one more reason not to use a clickable <div>.
The event object
The function receives an event object that describes what happened:
const search = document.querySelector("#search");
search.addEventListener("input", (event) => {
const text = event.target.value.trim().toLowerCase(); // event.target: the element concerned
document.querySelectorAll(".city").forEach((li) => {
li.hidden = !li.textContent.toLowerCase().includes(text);
});
});
event.target is the element on which the event happened, and .value the content of a field. The hidden attribute hides an element.
Handling a form
By default, submitting a form reloads the page. To handle it in JavaScript, you block this behaviour with event.preventDefault():
const form = document.querySelector("#signup");
const error = document.querySelector("#error");
form.addEventListener("submit", (event) => {
event.preventDefault(); // no reload
const data = new FormData(form); // reads all the fields by their name
const age = Number(data.get("age"));
if (age < 13) {
error.textContent = "You must be at least 13 to sign up.";
form.elements.age.focus(); // takes the user back to the faulty field
return;
}
error.textContent = "";
console.log("Sign-up:", data.get("firstName"), age);
});
For the error message to be read by a screen reader, put it in a <p id="error" role="alert"> element: its content is announced as soon as it changes.
The function looks at event.target to know which button was clicked, and deletes the right row.
Text description of the animation
- The user clicks the "Delete" button on the third row.
- The event is created on the button: it's its target.
- Then it travels up through the parents: this is bubbling.
- The list has a click listener: it fires, even though the click happened on one of its descendants.
- The function looks at event.target to know which button was clicked, and deletes the right row.
Event delegation
An event bubbles up from the clicked element through all its parents: this is bubbling. You take advantage of it by putting a single listener on a parent, instead of one per element. It even works for elements added later:
const list = document.querySelector("#list");
list.addEventListener("click", (event) => {
const button = event.target.closest("button.delete");
if (!button) return; // the click wasn't on a Delete button
button.closest("li").remove();
});
closest(selector) goes up from an element to the first ancestor that matches, starting with the element itself.
Your turn
The search filterHTML · CSS · JS
Preview
Console
(Nothing in the console yet.)Your code runs in an isolated page, with no access to this site or the Internet · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Worked exercise
Worked exercise: the donation counter
A page contains a form #donation with a amount field (number) and a button, a paragraph #total and a paragraph #error (role="alert"). On each submission, without reloading the page: if the amount isn't a strictly positive number, display an error and put the focus back on the field; otherwise, add it to the total, display Total raised: €45 and empty the field.
Hint 1
Number("") is 0 and Number("abc") is NaN. Number.isFinite(x) && x > 0 rules out both cases.Hint 2
form.reset() empties all the form's fields.Show the solution and common mistakes
const form = document.querySelector("#donation");
const totalDisplay = document.querySelector("#total");
const error = document.querySelector("#error");
let total = 0;
form.addEventListener("submit", (event) => {
event.preventDefault();
const amount = Number(form.elements.amount.value);
if (!Number.isFinite(amount) || amount <= 0) {
error.textContent = "Enter a positive amount.";
form.elements.amount.focus();
return;
}
error.textContent = "";
total += amount;
totalDisplay.textContent = `Total raised: €${total}`;
form.reset();
});
Common mistakes:
- Listening to
clickon the button instead ofsubmiton the form: the Enter key in the field submits the form without going through your code, and the page reloads. - Forgetting
event.preventDefault(): the page reloads and the total goes back to zero.
Summary
- 1addEventListener(type, function) calls the function on every event.
- 2The event object gives the target (event.target); preventDefault blocks the default behaviour.
- 3A form is handled on the submit event, with FormData to read the fields.
- 4Events bubble up through the parents: a single listener is enough for a whole list.
- 5You pass the function (add), you don't call it (add()).
Your progress is saved on this device. Create a free account to keep your progress on all your devices.