Lesson 10 / 10100%

Lesson 10

Events

23 min

addEventListener : react to clicks, input and loading.

What is an event in JavaScript?

Definition

An event is a signal sent by the browser to indicate that something has happened (a user action or a change in the state of the page). You listen for it with an event handler : a function that runs automatically every time the event occurs.

An event is an action detected by the browser: a mouse click, a key pressed on the keyboard, a form being submitted, the page being scrolled, an image finishing loading... JavaScript lets you listen for these events and run code in response, using the addEventListener method. This is the mechanism that makes a website truly interactive.

Without events, a script would run only once, from top to bottom, and then stop. With them, you adopt a reaction mindset: you declare in advance "when this happens, do that", and the browser calls your function at the right moment, whether that is in a second or in an hour. This is called event-driven programming.

Listening for a click with addEventListener

click.js
const button = document.querySelector("#my-button");

button.addEventListener("click", () => {
  console.log("The button was clicked!");
});
  • The first argument is the event type to listen for (here, "click").
  • The second argument is the function that runs when the event occurs (it is called a "callback" or "event handler").
  • You can add several different listeners to the same element, for different events.

You can also add several listeners of the same type to the same element: they all run, in the order they were added. This is a decisive advantage over the old onclick property, which keeps only one function and overwrites the previous one.

multiple-listeners.js
const button = document.querySelector("#my-button");

button.addEventListener("click", () => console.log("First listener"));
button.addEventListener("click", () => console.log("Second listener"));
// One click logs both messages, in that order

The event object: information about the triggered action

The callback automatically receives an event object, which contains a lot of useful information about the triggered action: the element involved, the key pressed, the cursor position...

event-object.js
const field = document.querySelector("#name");

field.addEventListener("input", (event) => {
  console.log("Current value:", event.target.value);
});

document.addEventListener("keydown", (event) => {
  console.log("Key pressed:", event.key);
});
  • event.target refers to the element that triggered the event.
  • event.target.value lets you get the value of a form field at the moment of the event.
  • event.key contains the name of the key pressed, for example "Enter" or "a".
event-properties.js
document.addEventListener("click", (event) => {
  console.log(event.type);       // "click": the event type
  console.log(event.clientX);    // horizontal position of the mouse
  console.log(event.clientY);    // vertical position of the mouse
  console.log(event.shiftKey);   // true if the Shift key was held down
});

You can name this parameter whatever you like, but event ore are the conventions. If you don't need it, you can simply leave it out.

Handling a form submission

By default, an HTML form reloads the page when it is submitted. This is rarely the behavior you want in JavaScript, where you usually want to validate the data or send it without reloading.

form.js
const form = document.querySelector("form");

form.addEventListener("submit", (event) => {
  event.preventDefault(); // prevents the page from reloading

  const nameField = document.querySelector("#name");
  console.log("Form submitted with the name:", nameField.value);
});
  • event.preventDefault() cancels the browser's default behavior for this event.
  • It is also useful to stop a link (<a>) from navigating to its usual destination.

You listen for submit on the form and not on the submit button: that way, the submission is also intercepted when the user presses the Enter key in a field. Remember thatvalue always returns a string : usetrim() to remove unnecessary whitespace andNumber() to convert a number.

The most common events

  • click: a mouse click on an element.
  • input: the value of a form field changes (on every keystroke).
  • change: the value of a field changes and the field loses focus (useful for drop-down lists and checkboxes).
  • submit: a form is submitted.
  • keydown / keyup: a key is pressed or released.
  • mouseover / mouseout: the mouse enters or leaves an element.
  • load: a resource (page, image) has finished loading.
  • DOMContentLoaded: the page's HTML is fully loaded and ready to be manipulated.
  • focus / blur: a field gains or loses focus (for example, to validate a field when the user leaves it).
  • scroll: the page or an element is scrolled.
  • resize: the browser window is resized (listened for on window).
various-events.js
const field = document.querySelector("#email");

field.addEventListener("focus", () => field.classList.add("active"));
field.addEventListener("blur", () => field.classList.remove("active"));

window.addEventListener("scroll", () => {
  console.log("Vertical position:", window.scrollY);
});

Event propagation

When you click a button located inside a <div>, the event does not concern only the button: it then bubbles up to its parents, all the way to document. This phenomenon is called bubbling .

propagation.js
// <div id="box"><button id="button">Click</button></div>
const box = document.querySelector("#box");
const button = document.querySelector("#button");

box.addEventListener("click", () => console.log("Click caught by the box"));

button.addEventListener("click", (event) => {
  console.log("Click on the button");
  // event.stopPropagation(); // would stop the event from bubbling up to the box
});
// A click on the button logs both messages, button first
  • event.target is always the element that was actually clicked , whereas event.currentTarget is the element the listener is attached to.
  • event.stopPropagation() stops the bubbling, but it should be used sparingly because it can interfere with other listeners.

Event delegation

Thanks to propagation, you can attach a single listener to the parent instead of one listener per child. It is more efficient, and it even works for elements added to the page later.

delegation.js
const list = document.querySelector("ul");

list.addEventListener("click", (event) => {
  const item = event.target.closest("li"); // finds the clicked <li>
  if (!item) return;                       // click outside any item

  item.classList.toggle("done");
});

Removing an event listener

Sometimes you need to remove a listener, for example to prevent an action from firing several times. This requires passing a named function (not an anonymous one) toaddEventListener, so that you can reference it afterwards inremoveEventListener.

remove-event-listener.js
function handleClick() {
  console.log("Click detected!");
}

const button = document.querySelector("#my-button");
button.addEventListener("click", handleClick);

// Later, to remove the listener:
button.removeEventListener("click", handleClick);

For a listener that should run only once , there is a shortcut: the once option, passed as the third argument. The listener is then removed automatically after it first fires.

once-option.js
button.addEventListener("click", () => {
  console.log("This message will only be displayed once");
}, { once: true });

Complete example: a click counter

click-counter.js
let counter = 0;

const button = document.querySelector("#my-button");
const display = document.querySelector("#counter");

button.addEventListener("click", () => {
  counter++;
  display.textContent = counter;
});

This example nicely illustrates how JavaScript ties together the three notions covered in this course: selecting DOM elements, updating their content, and reacting to a user event.

Anonymous function or named function?

The handler can be written in two ways. An anonymous function (often an arrow function) is handy for short code used only once. A named function is preferable as soon as the code is long, reused on several elements, or when you will need to remove the listener later.

anonymous-or-named.js
// Anonymous function: short and local
button.addEventListener("click", () => console.log("Click"));

// Named function: reusable and readable
function showMessage(event) {
  console.log("Event:", event.type);
}

button.addEventListener("click", showMessage);
link.addEventListener("click", showMessage); // same function, different element

In addEventListener, you pass the function itself, without parentheses : the browser is the one that will call it at the right moment.

Listening to several elements at once

addEventListener applies to a single element. To listen to every element in a list obtained with querySelectorAll, loop over it with forEach and attach a listener to each one.

multiple-elements.js
const buttons = document.querySelectorAll(".btn");

buttons.forEach((button) => {
  button.addEventListener("click", (event) => {
    console.log("Button clicked:", event.currentTarget.textContent);
  });
});

If the list is long or changes over time, the event delegation covered earlier is still the better choice.

Reacting to the keyboard

The keydown and keyup events let you create shortcuts or validate a field with the Enter key. Theevent.key property gives the readable name of the key.

keyboard.js
const field = document.querySelector("#search");

field.addEventListener("keydown", (event) => {
  if (event.key === "Enter") {
    console.log("Searching for:", field.value);
  }

  if (event.key === "Escape") {
    field.value = ""; // clears the field
  }
});

// Global shortcut: Ctrl + S (Cmd + S on Mac)
document.addEventListener("keydown", (event) => {
  if ((event.ctrlKey || event.metaKey) && event.key === "s") {
    event.preventDefault(); // prevents the browser's "Save as" dialog
    console.log("Custom save");
  }
});
  • keydown repeats as long as the key is held down, whereas keyup fires only once, when the key is released.
  • event.ctrlKey, event.metaKey, event.shiftKey and event.altKey indicate whether a modifier key is held down (metaKey is the Cmd key on Mac).

Common mistakes

  • Writing addEventListener("click", myFunction()) with parentheses: the function is called immediately instead of being passed. You must write myFunction without parentheses.
  • Trying to add a listener to an element that cannot be found (null): check your selector and when your script runs.
  • Forgetting preventDefault() in a submit handler: the page reloads and the entered data disappears.
  • Trying to remove a listener that was added with an anonymous function: removeEventListener does not recognize it.

Exercise 1: a click counter

Create an HTML page with:

  1. A button <button id="my-button">Click me</button>
  2. An element <p id="counter">0</p>
  3. In JavaScript, add a click event listener to the button that increments a counter and updates the paragraph's text on every click.
  4. Then add a text field and log its value to the console on every keystroke, using the input event.

Exercise 2: a contact form

Create a form with a first-name field and a submit button:

  1. Listen for the submit event and call event.preventDefault().
  2. If the field is empty (after trim()), display an error message in a paragraph.
  3. Otherwise, display "Hello" followed by the first name, then clear the field.

Exercise 3: event delegation

Create a <ul> list with five items:

  1. Attach a single click listener to the list.
  2. When an <li> is clicked, toggle the "done" class with classList.toggle.
  3. Add a button that creates a new item in the list, and check that clicking it works too.

Key takeaways

  • addEventListener lets you react to a user action.
  • The event object passed to the callback contains useful information about the triggered action.
  • event.preventDefault() cancels the browser's default behavior (reloading, navigation...).
  • The most common events are click, input, submit and keydown.
  • Events bubble up from the element to its parents: delegation takes advantage of this with a single listener on the parent.
  • To remove a listener, use a named function; for a one-time trigger, use the once option.