Course outline · 0% complete

0/30 lessons0%

Course overview →

Events

lesson 8-3 · ~9 min · 26/30

Listening for events

Your programs so far ran top to bottom and exited. A page cannot work that way: it must sit idle and respond whenever the user acts, at any time, in any order. Events are the mechanism that inverts control — the browser watches for actions and calls your functions when they happen.

An event is anything that happens in the page: a click, a keypress, a form submit. You react by registering a listener, a function the browser calls whenever the event fires:

const button = document.querySelector("#save");

button.addEventListener("click", () => {
  button.textContent = "Saved!";
});

Event names you will use constantly: click, input (every keystroke in a field), change, submit (fired by the form), keydown.

The listener receives an event object with the details. One of its methods matters immediately: on a form's submit, calling event.preventDefault() stops the browser's built-in submission (which reloads the page), so your JavaScript can handle the data instead:

form.addEventListener("submit", (event) => {
  event.preventDefault();
  // validate, then decide what happens
});

That is exactly how the capstone's form works in lesson 9-3.

Code exercise · javascript

The browser keeps a list of listeners per event name and calls each one when that event fires. This tiny simulation IS the mental model. Run it and predict the four lines before you look.

Code exercise · javascript

Your turn: listeners can keep state between events using a variable from the outer scope. Register ONE click listener that counts how many times click has fired and logs "clicks: N" each time.

Now do it in a real page. In the JS pane: select the button and the #count span, then add a click listener that increments a counter variable and writes it into the span's textContent.

Quiz

You want a character counter under a textarea that updates as the user types. Which event do you listen for?

Quiz

What does event.preventDefault() do inside a submit listener?