Tutorials / JavaScript Fundamentals / Events: reacting to clicks, input and forms

Events: reacting to clicks, input and forms

15 min read javascript
Course contents (16 lessons)
  1. Getting started
  2. What is JavaScript and where does it run?
  3. Variables with let and const
  4. Values and operators
  5. Data types: numbers, strings, booleans, null and undefined
  6. Operators: arithmetic, comparison and logical
  7. Strings and template literals
  8. Making decisions and repeating work
  9. Conditionals: if, else and switch
  10. Loops: for, while and for...of
  11. Functions
  12. Functions: declarations, parameters and return values
  13. Arrow functions and callbacks
  14. Arrays and objects
  15. Arrays: creating, reading and changing lists
  16. Array methods: map, filter, find and reduce
  17. Objects: properties, methods and copying
  18. Scope and the browser
  19. Scope and closures, gently
  20. The DOM: selecting and changing elements
  21. Events: reacting to clicks, input and forms
  22. Final project
  23. 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

EventWhen it fires
clickMouse click or tap
inputValue of a field changes
changeA field loses focus after a change, or a select or checkbox changes
submitA form is submitted
keydownA key is pressed
DOMContentLoadedThe HTML is parsed and the DOM is ready

Common mistakes

  • Calling the handler. addEventListener("click", doWork()) runs doWork immediately. Pass doWork without 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 submit event.
  • 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.value inside the handler.

Try it yourself

  1. Make a button that toggles a dark class on body each time it is clicked.
  2. Build a text box with a live character counter below it, using the input event.
  3. Make a form that adds the typed name to a list on submit and clears the box.
  4. Use event delegation on a list so that clicking an item removes it.
javascript
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