Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
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.

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.

The shortcut

Read every listener as a sentence: "When this element gets this event, run this function." If the sentence mentions many similar children, move the listener to their shared parent and use delegation.

Wiring up twelve Add buttonsStep 1 of 4
  1. Say the sentence

    "When any Add button is clicked, add its item to the basket." Many similar children: delegate.

The classic bug is button.addEventListener("click", addRye()). The brackets call addRye immediately while the page loads and pass its result, undefined, as the handler. Nothing happens on click.

Drills

Answer fast — trust the rule.

quick drill

What is wrong with button.addEventListener("click", addRye());?

quick drill

A form handler validates fields in JavaScript. What stops the browser from also loading a new page?

quick drill

Why can one click listener on .menu handle clicks on buttons inside every card?

quick drill

Which event fires each time the visitor types a character into a text field?

Remember

  • Listen on an element, pass a function, and the browser calls it later.
  • "When this element gets this event, run this function"; many similar children means delegate to the parent.
  • Trap: brackets after the handler name call it right away.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainTwelve buttons, one listener

The bakery menu has twelve Add buttons, and more cards may be added later. Explain how you would handle clicks on all of them with a single listener, and what goes wrong if someone writes button.addEventListener("click", addItem()).