Events: reacting to clicks, input and forms
Course contents (16 lessons)
- Getting started
- What is JavaScript and where does it run?
- Variables with let and const
- Values and operators
- Data types: numbers, strings, booleans, null and undefined
- Operators: arithmetic, comparison and logical
- Strings and template literals
- Making decisions and repeating work
- Conditionals: if, else and switch
- Loops: for, while and for...of
- Functions
- Functions: declarations, parameters and return values
- Arrow functions and callbacks
- Arrays and objects
- Arrays: creating, reading and changing lists
- Array methods: map, filter, find and reduce
- Objects: properties, methods and copying
- Scope and the browser
- Scope and closures, gently
- The DOM: selecting and changing elements
- Events: reacting to clicks, input and forms
- Final project
- Project: build a to-do list in the browser
Events make pages interactive
An event is something that happens on the page: a click, a key press, a form submit, a page load. You tell the browser which function to call when it happens. That function is an event handler.
addEventListener
<button id="btn">Click me</button>
<p id="output"></p>
const button = document.querySelector("#btn");
const output = document.querySelector("#output");
let clicks = 0;
button.addEventListener("click", () => {
clicks++;
output.textContent = `You clicked ${clicks} times`;
});
addEventListener takes the event name and a callback. Do not call the callback yourself, just pass it. The browser calls it each time the event happens. Because the callback is a closure, it can read and update clicks between clicks.
You can attach as many listeners as you like to one element. To remove one, you need a named function: button.removeEventListener("click", handleClick).
The event object
The browser gives your handler an object with details about what happened:
document.addEventListener("keydown", event => {
console.log(event.key); // "a", "Enter", "ArrowUp"
});
button.addEventListener("click", event => {
console.log(event.target); // the element that was clicked
console.log(event.clientX, event.clientY);
});
event.target is the element that triggered the event. That is useful when one handler serves many elements.
Reading input
For text fields, the input event fires on every change:
<input id="name" placeholder="Your name">
<p id="greeting"></p>
const nameInput = document.querySelector("#name");
const greeting = document.querySelector("#greeting");
nameInput.addEventListener("input", () => {
const name = nameInput.value.trim();
greeting.textContent = name ? `Hello, ${name}!` : "";
});
Remember that .value is always a string. For a number field, convert it: Number(input.value).
Forms and preventDefault
When you submit a form, the browser by default sends a request and reloads the page. For JavaScript apps you want to handle it yourself, so you stop the default action.
<form id="signup">
<input name="email" type="email" required>
<button type="submit">Join</button>
</form>
<p id="status"></p>
const form = document.querySelector("#signup");
const status = document.querySelector("#status");
form.addEventListener("submit", event => {
event.preventDefault();
const email = form.elements.email.value.trim();
status.textContent = `Thanks, we will write to ${email}`;
form.reset();
});
Listen to submit on the form, not click on the button. That way pressing Enter in a field also works, and the browser's built-in required and type="email" checks still run.
Event bubbling
Most events bubble. When you click a button inside a list inside a div, the click event fires on the button, then on the list, then on the div, and so on up to document. Because of this, you can listen once on a parent instead of on every child.
Event delegation
Imagine a list where items are added over time. Attaching a listener to each item is tedious, and new items would have none. Instead, listen on the list and look at event.target:
<ul id="tasks">
<li>Write code</li>
<li>Test code</li>
</ul>
const tasks = document.querySelector("#tasks");
tasks.addEventListener("click", event => {
const li = event.target.closest("li");
if (!li) return;
li.classList.toggle("done");
});
closest("li") finds the nearest list item at or above the clicked element. If the click was somewhere else inside the list, it returns null and we exit. Now any item, including ones added later, responds to clicks. I use delegation for every dynamic list. The final project depends on it.
Other useful events
| Event | When it fires |
|---|---|
click | Mouse click or tap |
input | Value of a field changes |
change | A field loses focus after a change, or a select or checkbox changes |
submit | A form is submitted |
keydown | A key is pressed |
DOMContentLoaded | The HTML is parsed and the DOM is ready |
Common mistakes
- Calling the handler.
addEventListener("click", doWork())runsdoWorkimmediately. PassdoWorkwithout brackets. - Forgetting preventDefault in a submit handler. The page reloads and your changes vanish.
- Listening to click on the submit button. Use the form's
submitevent. - Adding listeners inside a loop of events. Registering the same handler again and again causes it to run many times.
- Reading the value once and expecting it to update. Read
input.valueinside the handler.
Try it yourself
- Make a button that toggles a
darkclass onbodyeach time it is clicked. - Build a text box with a live character counter below it, using the
inputevent. - Make a form that adds the typed name to a list on submit and clears the box.
- Use event delegation on a list so that clicking an item removes it.
const button = document.querySelector("#btn");
const output = document.querySelector("#output");
let clicks = 0;
button.addEventListener("click", () => {
clicks++;
output.textContent = `You clicked ${clicks} times`;
});
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account