Events: responding to clicks and typing
Make pages interactive with addEventListener: respond to button clicks, live typing and form submission, use the event object and preventDefault, and keep interactions accessible.
šÆ By the end of this lesson you will be able to:
- Run code when something happens with addEventListener
- Use click, input and submit events and the event object
- Stop a form reloading the page with preventDefault
Outline
What you'll learn and why it matters
So far your scripts run once, when the page loads. Real pages wait for people and react: a button is clicked, a key is pressed, a form is sent. These are events. Handling events is what turns a page into an app.
Listening for a click
element.addEventListener("click", function) says: *whenever this element is clicked, run this function*. The function is called an event handler or listener.
const button = document.querySelector("#add");
const output = document.querySelector("#count");
let count = 0;
button.addEventListener("click", () => {
count++;
output.textContent = `Cups ordered: ${count}`;
console.log(`Clicked ${count} times`);
});Show the HTML this script works with
<button type="button" id="add">Add a cup of chai</button>
<p id="count" aria-live="polite">Cups ordered: 0</p>Live preview: try it
Console
Nothing logged yet.
Click the button in the preview a few times and watch the page and the console. Notice that count is declared outside the function: it must survive between clicks.
Common events
| Event | Fires when | Typical use |
|---|---|---|
click | An element is clicked, tapped, or activated with Enter/Space on a button | Buttons, menus |
input | The value of a text box changes, on every key press | Live search, character counters |
change | A select, checkbox or radio button changes | Filters, settings |
submit | A form is sent (button click or Enter in a field) | Forms |
keydown | A key is pressed | Keyboard shortcuts |
Reacting to typing
The input event fires on every change. Read the current text with .value:
const box = document.querySelector("#bio");
const counter = document.querySelector("#remaining");
const limit = 60;
box.addEventListener("input", () => {
const left = limit - box.value.length;
counter.textContent = `${left} characters left`;
counter.classList.toggle("over", left < 0);
});Show the HTML and CSS this script works with
HTML
<label for="bio">Short bio</label><br>
<textarea id="bio" rows="3" cols="30"></textarea>
<p id="remaining" aria-live="polite">60 characters left</p>CSS
.over { color: #b91c1c; font-weight: 700; }Live preview: try it
Console
Nothing logged yet.
classList.toggle("over", left < 0) adds the class when the second argument is true and removes it when it is false. The text also changes, so the warning does not depend on colour alone.
The event object
Every listener receives an event object describing what happened. event.target is the element the event happened on. One listener can then handle several buttons:
const sizes = document.querySelector("#sizes");
const chosen = document.querySelector("#chosen");
sizes.addEventListener("click", (event) => {
const button = event.target.closest("button");
if (!button) return;
chosen.textContent = `You chose: ${button.dataset.size}`;
});Show the HTML this script works with
<div id="sizes">
<button type="button" data-size="Small">Small</button>
<button type="button" data-size="Medium">Medium</button>
<button type="button" data-size="Large">Large</button>
</div>
<p id="chosen" aria-live="polite">No size chosen</p>Live preview: try it
Console
Nothing logged yet.
This is called event delegation: one listener on the parent instead of one on every button. closest("button") finds the clicked button even if the click landed on something inside it, and returns null if the click was on the gap between buttons, so we return early.
Forms and preventDefault
When a form is submitted, the browser normally sends it to the server and loads a new page. For forms you handle in JavaScript, stop that with event.preventDefault():
const form = document.querySelector("#signup");
const message = document.querySelector("#message");
form.addEventListener("submit", (event) => {
event.preventDefault();
const name = document.querySelector("#name").value.trim();
message.textContent = `Thanks, ${name}! You are on the list.`;
form.reset();
});Show the HTML this script works with
<form id="signup">
<label for="name">Your name</label>
<input type="text" id="name" required>
<button type="submit">Join the newsletter</button>
</form>
<p id="message" aria-live="polite"></p>Live preview: try it
Console
Nothing logged yet.
Listen for submit on the form, not click on the button: submit also fires when someone presses Enter in a field, and the browser still checks required fields first. form.reset() clears the fields afterwards.
Practice
Guided exercise
Like button
Make a button that toggles between ā” Like and ā„ Liked and keeps a like count in #likes.
- Store
let liked = false;andlet likes = 10;outside the listener. - In the click listener, flip
likedwithliked = !liked. - Add 1 to
likesif now liked, otherwise subtract 1. - Update the button text and
#likes, and setaria-pressedon the button.
Show the solution
const button = document.querySelector("#like");
const counter = document.querySelector("#likes");
let liked = false;
let likes = 10;
button.addEventListener("click", () => {
liked = !liked;
likes += liked ? 1 : -1;
button.textContent = liked ? "ā„ Liked" : "ā” Like";
button.setAttribute("aria-pressed", String(liked));
counter.textContent = `${likes} likes`;
});Show the HTML this script works with
<button type="button" id="like" aria-pressed="false">ā” Like</button>
<p id="likes" aria-live="polite">10 likes</p>Live preview: try it
Console
Nothing logged yet.
How to get there: The state (liked, likes) lives outside the listener so it is remembered between clicks. aria-pressed tells screen readers the button is a toggle and whether it is on.
Your turn
Live greeting
As someone types in #name, show Hello, <name>! in #greeting. If the box is empty, show Hello, stranger!.
Show the solution
const input = document.querySelector("#name");
const greeting = document.querySelector("#greeting");
input.addEventListener("input", () => {
const name = input.value.trim();
greeting.textContent = `Hello, ${name || "stranger"}!`;
});Show the HTML this script works with
<label for="name">Your name</label>
<input type="text" id="name">
<p id="greeting" aria-live="polite">Hello, stranger!</p>Live preview: try it
Console
Nothing logged yet.
How to get there: An empty string is falsy, so name || "stranger" uses the fallback when nothing (or only spaces) was typed. trim() handles the spaces.
Common mistakes
Calling the function in addEventListener: handle()
You see: It runs once when the page loads, and never on click
Fix: Pass the function itself: addEventListener("click", handle).
Listening for click on a submit button instead of submit on the form
You see: Enter in a field skips your code, or the page reloads
Fix: Listen for submit on the form and call event.preventDefault().
Forgetting event.preventDefault()
You see: The page reloads and your message vanishes
Fix: Call it first thing in a submit handler.
Making a clickable <div>
You see: Keyboard users cannot reach or activate it
Fix: Use a real <button type="button">.
Declaring the counter inside the listener
You see: It resets to 0 on every click
Fix: Keep values that must be remembered outside the listener.
Recap
addEventListener(type, function)runs the function every time the event happens.- click for buttons, input for live typing, change for choices, submit for forms.
- The event object's target is the element involved; delegation uses one listener for many.
- Call event.preventDefault() in submit handlers; use real buttons and aria-live for updates.
Key terms
- Event
- Something that happens on the page, such as a click, key press or form submission.
- Event listener
- A function registered to run when a particular event happens.
- preventDefault
- A method that stops the browser's normal action for an event, such as reloading on submit.
Check your understanding
Answer all 4 questions, then check your answers to see an explanation for each one.
1. Which event fires on every key press in a text box?
2. What does `event.preventDefault()` do in a submit handler?
3. What is wrong with `button.addEventListener("click", save())`?
4. Why should a click counter variable be declared outside the listener?
Mark this lesson complete
Finished this lesson?
When you have worked through the examples and exercises, mark it complete to save your progress.