DEV Community

Cover image for Optimizing JavaScript Event Handling: Bubbling and Delegation
Jaligama Satyaveer
Jaligama Satyaveer

Posted on

Optimizing JavaScript Event Handling: Bubbling and Delegation

JavaScript events are everywhere on the web. Clicking a button, typing in a text box, or even moving your mouse triggers an event. But have you ever wondered how these events travel through the DOM? That’s where event bubbling and event delegation come into play.

Let’s break it down in a way that actually makes sense!

What is an Event in JavaScript?

Before jumping into bubbling and delegation, let’s quickly define what an event is. An event is basically an action that happens in the browser, like a click or a key press. You can listen to these events using JavaScript and decide what happens when they occur.

Here’s a simple example of handling a button click:

const button = document.getElementById("myButton");
button.addEventListener("click", () => {
    alert("You clicked the button!");
});
Enter fullscreen mode Exit fullscreen mode

What is Event Bubbling?

Event bubbling is when an event starts at the target element and moves up through its ancestors. Think of it like bubbles in water - once they are created, they rise to the top.

How Event Bubbling Works
Imagine this HTML structure:

<div id="parent">
    <button id="child">Click Me</button>
</div>
Enter fullscreen mode Exit fullscreen mode

Now, let’s add event listeners to both the parent <div> and the child <button>:

document.getElementById("parent").addEventListener("click", () => {
    console.log("Parent clicked");
});

document.getElementById("child").addEventListener("click", () => {
    console.log("Child clicked");
});
Enter fullscreen mode Exit fullscreen mode

What Happens When You Click the Button?
When you click the button, you’ll see:

Child clicked
Parent clicked
Enter fullscreen mode Exit fullscreen mode

Why? Because the event first fires on the button and then bubbles up to the parent.

Stopping Event Bubbling
Sometimes, you don’t want an event to bubble up. You can stop it using event.stopPropagation()

document.getElementById("child").addEventListener("click", (event) => {
    console.log("Child clicked");
    event.stopPropagation();
});
Enter fullscreen mode Exit fullscreen mode

Now, clicking the button will only log Child clicked and won’t trigger the parent’s event.


What is Event Delegation?

Instead of adding event listeners to multiple elements, you can use event delegation by placing a listener on a parent element and checking which child was clicked.

Why Use Event Delegation?

  • You don’t have to attach event listeners to each individual child element.
  • It works on dynamically added elements.
  • It improves performance when dealing with lots of elements.

Example: Handling Clicks on List Items
Consider this HTML:

<ul id="listContainer">
    <li class="list-item">Item 1</li>
    <li class="list-item">Item 2</li>
</ul>
<button id="addItem">Add Item</button>
Enter fullscreen mode Exit fullscreen mode

Instead of adding an event listener to each list item, we add one to the parent <ul> and check which item was clicked:

document.getElementById("listContainer").addEventListener("click", (event) => {
    if (event.target.classList.contains("list-item")) {
        console.log("Clicked on: " + event.target.textContent);
    }
});
Enter fullscreen mode Exit fullscreen mode

Now, let’s add new list items dynamically:

document.getElementById("addItem").addEventListener("click", () => {
    const newItem = document.createElement("li");
    newItem.classList.add("list-item");
    newItem.textContent = "New Item";
    document.getElementById("listContainer").appendChild(newItem);
});
Enter fullscreen mode Exit fullscreen mode

Even though the new list items were added later, they will still trigger the click event. That’s the power of event delegation!

Wrapping Up

Understanding event bubbling helps you know how events travel up the DOM, and event delegation helps you manage events efficiently. Together, they make your JavaScript code cleaner and more optimized.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

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

Okay