DEV Community

Carsten Behrens
Carsten Behrens

Posted on • Originally published at carstenbehrens.com

Event bubbling for Dummies

Before we can go into what Event bubbling is, we have to make sure that we understand what an Event is.

An Event is something that happens on a webpage, for example, a user clicking on a button or an error that occurs.

Events are fired and then handled via an event handler. (Or ignored if we don't have any event handler listing for that Event)

Events in action

An example of an event being fired and an event handler looks like this.

<button>Click Me</button>
<script>
    document.querySelector("button").addEventListener("click", (event) => console.log(event))
</script>
Enter fullscreen mode Exit fullscreen mode

So what is happening here is the following:

  1. We search the button via the querySelector
  2. We attach an event listener
  3. We console.log the event

Now let's go into event bubbling.

Event bubbling

The example above is pretty straightforward, but what happens if we don't attach the event handler to the button directly?

<div>
    <button>Click Me</button>
</div>
<script>
    document.querySelector("div").addEventListener("click", (event) => console.log(event))
</script>
Enter fullscreen mode Exit fullscreen mode

In this case, we attach the event handler to the div that is the parent of the button.

Even though the event handler is not attached to the button, the event handler still gets called.

This is because the event "bubbles" up from the child element to the parent element and so on.

It is noteworthy that the event will keep "bubbling up" after an event handler has already handled it.

<div>
    <button>Click Me</button>
</div>
<script>
    document.querySelector("div").addEventListener("click", (event) => console.log(event))
    document.querySelector("button").addEventListener("click", (event) => console.log(event))
</script>
Enter fullscreen mode Exit fullscreen mode

Both event handlers will be called.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay