What is Event bubbling and Event Capturing in JavaScript ? (original) (raw)

Last Updated : 14 Sep, 2021

Event bubbling and event capturing are the two interesting concepts of JavaScript. Before diving deep into these fascinating concepts, let us first know about what an event listener is? An event listener is basically a function that waits for an event to occur. That event can be anything like a mouse click event, submitting a form, pressing keys of a keyboard, etc.

An event listener contains three parameters and it can be defined using the following syntax.

.addEventListener(, , {capture : boolean});

Example 1: Let's take an example to understand event bubbling and event capturing.

HTML `

Welcome To GFG

GrandParent
Parent
Child
<script>
    const grandParent = document.getElementById("grandparent");
    const parent = document.getElementById("parent");
    const child = document.getElementById("child");

    grandParent.addEventListener("click", (e) => {
        console.log("GrandParent");
    }, { capture: false });
    parent.addEventListener("click", (e) => {
        console.log("Parent");
    }, { capture: false });
    child.addEventListener("click", (e) => {
        console.log("Child");
    }, { capture: false });
</script>

`

Output:

When we clicked on the div with the child as its id, we should get the output as 'child' on our console. But unexpectedly, we are receiving a different output even we have not clicked on divs with parent and grandparent as their id. The concept of event bubbling comes into the picture. The child div lies inside the parent div as well as in the grandparent div. So, when the child div clicked, we indirectly clicked on both parent div and grandparent div. Thus, propagation is moving from inside to outside in the DOM or we can say events are getting bubble up.

Therefore, the process of propagating from the closest element to the farthest away element in the DOM (Document Object Modal) is called event bubbling.

Example 2: In the above example, let us change the value of the third parameter of addEventListener() and see what changes will be made in the output.

HTML `

<style>
    div {
        color: white;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
    }
    h2 {
        color: black;
    }
    #grandparent {
        background-color: green;
        width: 300px;
        height: 300px;
    }
    #parent {
        background-color: blue;
        width: 200px;
        height: 200px;
    }
    #child {
        background-color: red;
        width: 100px;
        height: 100px;
    }
</style>

Welcome To GFG

GrandParent
Parent
Child