Lesson 27 / 40

Event Listeners & Bubbling

Respond to user actions with event listeners, the event object, bubbling and preventDefault.

addEventListener

Attach a handler function that runs when the event fires.

const btn = document.querySelector("button");
btn.addEventListener("click", (event) => {
  console.log("Clicked!", event.target);
});

The event object

Every handler receives an event object — event.target is the actual element clicked, and event.preventDefault() stops default browser behavior.

Event bubbling

Events bubble up from the target element through its ancestors — a click on a button also triggers listeners on its parent div, unless stopped with event.stopPropagation().

Quick check: What does event.preventDefault() do?

  • Stops the event from bubbling
  • Removes the event listener
  • Reloads the page
  • Stops the browser's default action for that event
Answer

Stops the browser's default action for that event — For example, it stops a form's default submit-and-reload behavior — bubbling is a separate concern handled by stopPropagation().