Skip to the workspace
Pebellslearn by building
JavaScript  ›  Lesson

Events — Reacting to Visitors

JavaScript 15 minaddEventListener registers a handler function that the browser calls when an event happens, preventDefault cancels built-in actions, and bubbling lets one parent listener handle many children.

frontend / Events — Reacting to Visitors

Explore each scene at your own pace.

01 · The rule

The rule

Events — Reacting to Visitors

A script that runs once when the page loads can mark the rye sold out. But the "Add to order" buttons must do something when they are clicked, and the cake form must check the date when it is submitted. Browsers report every click, key press and submission as an event, and your code can listen for them.

The rule

Listen on an element, pass a function, and the browser calls it later.

const button = document.querySelector("#add-rye");

function addRye(event) {
  basket.push("Rye");
  updateBasket();
}

button.addEventListener("click", addRye);
  • addEventListener(type, handler) takes the event type as a string and the handler, the function to run.
  • Notice addRye has no brackets. You are handing over the function itself for the browser to call later, not calling it now.
  • The browser passes an event object to the handler. event.target is the element the event happened on.

Common event types: click, input (a field's value changed), change, submit (a form is being sent), keydown, and DOMContentLoaded (the HTML has been parsed).

Stopping the default. Some events come with a built-in action: submitting a form loads a new page, clicking a link navigates. When your script handles it instead, cancel the default:

form.addEventListener("submit", (event) => {
  event.preventDefault();
  // check the fields and send them with JavaScript instead
});

Bubbling and delegation. After an event fires on an element, it bubbles up through each ancestor, all the way to document. That means one listener on a parent can handle clicks on all its children, even ones added later:

document.querySelector(".menu").addEventListener("click", (event) => {
  const button = event.target.closest("button");
  if (button) {
    basket.push(button.dataset.item);
    updateBasket();
  }
});

This pattern is called event delegation. closest("button") walks up from whatever was clicked, perhaps an icon inside the button, to the button itself. dataset.item reads that button's data-item attribute.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.