DEV Community

Cover image for What is event bubbling?
Rodman Lavalais
Rodman Lavalais

Posted on • Updated on

What is event bubbling?

Event handling is a foundational aspect of web development, that deals with the Document Object Model, allowing developers to create interfaces that are dynamic and enables interactivity. With the ample amount of knowledge out there surrounding event handling, event bubbling is a very essential feature to apprehend. With a base understanding of what event bubbling is, and how useful it is, developers acquire the ability to build powerful and structured web applications. It's name may trick you into thinking it's a small fun feature that doesn't require any usefulness, but soon you'll understand significance of it's usage.

Event bubbling is a appliance in the Document Object Model, where the event on inner most target element is effectively triggered, then successfully propagated through the rest of the Document Object Model tree. In this instance, that same event is transferred to its' ancestors (parent elements), upwards in its' hierarchical manner, until it finally reaches the root of the Document Object Model.

Below is an visual example on how event bubbling works, with a simple HTML document including nested elements:

<div id="element3">
  <div id="element2">
    <button id="element1">Click Me</button>
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

Let's also add some attached event listeners to each of these elements:

document.getElementById('element3').addEventListener('click', function() {
  console.log('Element3 has been clicked!');
});

document.getElementById('element2').addEventListener('click', function() {
  console.log('Element2 has been clicked!');
});

document.getElementById('element1').addEventListener('click', function() {
  console.log('Element1 has been clicked!');
});
Enter fullscreen mode Exit fullscreen mode

Now let's say the "Click Me" button get's clicked, three things here would happen in order. First, the click function would execute it's code block, resulting in a console.log of "Element1 has been clicked!". Next, that same event listener would then bubble (transfer) up the hierarchical structure, going to it's parent element, which is a div element that holds the id of "element2". Then the event handler in this element would be executed, resulting in a console.log of "Element2 has been clicked!". Bubbling one more time to the root, which in this example is the div element that holds the id of "Element3". Last but not least, it's event listener would be executing, resulting in "Element3 has been clicked!"

In the showcased example above, in short term every event listener was invoked starting from the inner most element, then propagating upwards in the hierarchical straight the Document Object Model represents.

Event handlers can be extremely powerful, reducing the amount of code written. They allow developers to apply the event listeners to parent elements, instead of applying them to every single child element, greatly reducing the amount of code needed.

For example, below is an example of how event bubbling could be significantly useful in a simple visual manner.

<div class="New Orleans">
    <div class="ward" id="3rd">3rd Ward</div>
    <div class="ward" id="7th">7th Ward</div>
    <div class="ward" id="9th">9th Ward</div>
</div>

<script>
    // Attaching event listeners to each child element individually
    document.getElementById('3rd').addEventListener('click', function () {
        console.log('Clicked on 3rd Ward AKA the best ward');
    });

    document.getElementById('7th').addEventListener('click', function () {
        console.log('Clicked on 7th ward');
    });

    document.getElementById('9th').addEventListener('click', function () {
        console.log('Clicked on 9th ward');
    });

</script>
Enter fullscreen mode Exit fullscreen mode

With this example above, event bubbling is not being used, so an event listener would have to be added to each individual child element, to invoke the event handlers. As you can imagine, if there were a large amount of content, this would be very irritating.

Now below, let's do this same thing, but with an event bubbler on the parent element!

<div class="New Orleans" id="wardSelector">
    <div class="ward" id="3rd">3rd Ward</div>
    <div class="ward" id="7th">7th Ward</div>
    <div class="ward" id="9th">9th Ward</div>
</div>

<script>
    // Attaching event listeners to each child element individually
    document.getElementById('wardSelector').addEventListener('click', function (event) {
        if (event.target.classList.contains("ward")){
            console.log('Clicked on ' + event.target.textContent);  
            //.target refers to the specific element that triggered the event, in the event object
            //.textContent dispatches the text content of the specific element
        }
    });

</script>
Enter fullscreen mode Exit fullscreen mode

Here the outcome is the same, however the code has been greatly reduce!

Now thinks about all the awesome components or aspects that can be creature using a feature like this. Above just shows the tip of the ice berg, imagine what a team of individuals combined with the determination of creating an mind blowing application could create. The possibilities could be limitless, all while being given the option to reduce the amount of code that has to be written as much as possible! So much data could be stored, so many options or objectives could be visualized and represented. All because of a very critical feature, that has a fun goofy name like "event bubbler"!

After being shown the awesome examples above, it becomes quite clear to understand that event bubbling is a foundational feature inside of JavaScript, when it comes to the topic of event handling. When it's present, it authorizes well structured web applications, which is involved in interactivity by developers. By having a clear understand of the how critical and necessary event bubbling is, a developer can easily appreciate its importance when it comes to the topic web development. The consequence of it involves developers being able to implement well polished, sustainable code.

Sources:
https://www.youtube.com/watch?v=KaHZdW02Tg0&pp=ygUWV2hhdCBpcyBldmVudCBidWJibGluZw%3D%3D

https://www.freecodecamp.org/news/event-bubbling-in-javascript/#:~:text=What%20is%20Event%20Bubbling%3F,gets%20to%20the%20root%20element.

https://en.wikipedia.org/wiki/Event_bubbling#:~:text=Event%20bubbling%20is%20a%20type,object%20(Provided%20the%20handler%20is

https://www.loginradius.com/blog/engineering/javascript-events-bubbling-capturing-and-propagation/#:~:text=Propagation%20refers%20to%20how%20events,until%20it%20reaches%20its%20destination.

https://www.youtube.com/watch?v=N9vEXAWPynU&ab_channel=DeeecodeTheWeb

Top comments (2)

Collapse
 
10xlearner profile image
10x learner

Hi @cougarred1 !

Great article ! It is very clear about what event bubbling is and the advantage to use it !

Image description

Collapse
 
cougarred1 profile image
Rodman Lavalais

Thank you so much, truly appreciate you for taking the time to read!