Interactivity is built on events: user actions (a click, a hover, a key press) that your code can respond to.

Some common events

  • click — the user clicks an element.
  • mouseover — the mouse hovers over an element.
  • keydown — a key is pressed on the keyboard.

Listening for an event

You attach a response to an element with addEventListener:

const bouton = document.querySelector("button");
bouton.addEventListener("click", function() {
  alert("You clicked!");
});

The idea is simple: “when this event happens on this element, run this function“. The function you supply is known as a callback.

Key takeaway: addEventListener lets you respond to user actions. It is the heart of an interactive page.