Understanding Events

Interacting with web pages isn’t just about showing stuff. It’s about responding when users do something—click a button, press a key, move the mouse, submit a form. That’s where events come in. Events are how JavaScript listens and reacts to what’s happening in the browser.

What are they?

Actions that occur in the browser (clicks, mouse movements, key presses, form submissions, etc.)

In JavaScript, an event is anything that happens in the browser and might be interesting enough for us to respond to.

A few common ones:

  • click — when a user clicks an element.
  • keydown — when a key is pressed.
  • submit — when a form is submitted.
  • mouseover — when the mouse hovers over something.
  • change — when the value of an input changes.

These aren't just random things. They’re signals that tell us, “Hey, something just happened!”

To respond to these signals, we use event listeners. They’re like little sensors we attach to elements, saying: "When this happens, run this code."

javascript
1
2
3
4
5
          const button = document.querySelector("button");

button.addEventListener("click", function () {
  console.log("Button was clicked!");
});
        

The browser will wait for that click, and the moment it happens, the function inside addEventListener runs.

Event Flow: Learn about event capturing and bubbling

Here’s where things get slightly more advanced—but don’t worry, it’s actually pretty logical once you get the concept.

When an event happens, like a click, the browser doesn’t just say “click!” and stop there. Instead, it travels through the DOM in a specific order, like a ripple.

There are two main phases:

  1. 1
    Capturing phase – the event travels from the top of the DOM (<html>) down to the target element.
  2. 2
    Bubbling phase – then it bubbles back up from the target to the top.

Imagine clicking a button inside a <div> inside a <section> inside <body>. The event moves downward first, then upward.

Why does this matter? Because you can attach listeners in either phase.

By default, most events are handled during the bubbling phase. But you can choose to handle them during capturing by passing a third argument to addEventListener:

javascript
1
          element.addEventListener("click", handler, true); // true = capturing
        

Most of the time, you’ll just stick with bubbling. But knowing how the event travels helps when dealing with nested elements and avoiding bugs.

For example, suppose a button is inside a form. You might want to stop the form from submitting when the button is clicked. That’s where understanding event flow (and methods like event.stopPropagation() or event.preventDefault()) really pays off.