ILILCode
HomeJavaScriptThe browser

Events: making the page respond

addEventListener, the event object, and reading state back out of the DOM.

Lesson 11 of 23 in JavaScript10 min1 exercise

An event is something that happens: a click, a key press, a submit. You subscribe with addEventListener(type, handler). The handler runs later, when the event happens.

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

button.addEventListener("click", (event) => {
  console.log("clicked", event.target);
});

// Removing needs the same function reference:
function onKey(event) {
  if (event.key === "Escape") console.log("cancel");
}
document.addEventListener("keydown", onKey);
document.removeEventListener("keydown", onKey);

The handler receives an event object. event.target is the element that fired it, event.currentTarget is the element the listener is attached to. event.preventDefault() cancels the browser's default action.

One listener for many elements

Events bubble up from the target to its ancestors. Attach one listener to a parent and inspect event.target — this is event delegation, and it keeps working when you add children later.

Delegation
const list = document.querySelector("#list");

list.addEventListener("click", (event) => {
  const item = event.target.closest("li");
  if (!item) return;
  item.classList.toggle("done");
});

Try it

Click the button — twice, in code

main.js
console · output appears here

Exercises

Checked in your browser · hints and solutions included

01

Exercise

Wire up a counter

The button and the counter already exist. Add a click listener to #add that increases the number in #count by one each time. Keep the value as a number, not a string.

exercise.js
console · run your code or check the answer