DEV Community

Cover image for Capture VS Bubble
MR.H
MR.H

Posted on

Capture VS Bubble

On handling events in Javascript you may come across the bubble and capture phase. In this blog let's learn about both the phase

As you can see in the above example we have 3 div's Grandparent, parent, and child let's try to add an on-click listener to each of them.

const grandParent = document.getElementById('grandParent'),
    parent = document.getElementById('parent'),
    child = document.getElementById('child');

grandParent.addEventListener('click', () => {
    console.log('grand parent clicked')
})
parent.addEventListener('click', () => {
    console.log('parent clicked ')
})
child.addEventListener('click', () => {
    console.log('child clicked')
})
Enter fullscreen mode Exit fullscreen mode

The above code will produce the following output

//Clicking the green area
child clicked
parent clicked
grandParent clicked

//Clicking the red area
parent clicked
grandParent clicked

//Clicking the blue area
grandParent clicked
Enter fullscreen mode Exit fullscreen mode

As you can see in the above example event fired from the innermost element to the outermost element this phase is called Bubble. By default, events will be triggered during the bubble phase

Now let's try capture, To use capture we need to pass {capture: true} as the third argument to the addEventListener

grandParent.addEventListener('click', () => {
    console.log('grandparent clicked')
})
parent.addEventListener('click', () => {
    console.log('parent clicked')
})
child.addEventListener('click', () => {
    console.log('child clicked')
})

grandParent.addEventListener('click', () => {
    console.log('grandparent clicked from the capture')
},{capture:true})
parent.addEventListener('click', () => {
    console.log('parent clicked from the capture')
},{capture:true})
child.addEventListener('click', () => {
    console.log('child clicked from the capture')
},{capture:true})
Enter fullscreen mode Exit fullscreen mode

The above code will produce the following output

//Clicking the green area
grandparent clicked from capture
parent clicked from the capture
child clicked from the capture
child clicked
parent clicked
grandparent clicked

//Clicking the red area
grandparent clicked from capture
parent clicked from the capture
parent clicked
grandparent clicked

//Clicking the blue area
grandparent clicked from capture
grandparent clicked
Enter fullscreen mode Exit fullscreen mode

You can now see during the capture phase event is fired from the outermost element to the innermost element and then it will start the bubbling phase to bubble the event from the innermost element to the outermost element

Conclusion

Capture will move from the outermost element to the innermost element whereas Bubble moves from the innermost element to the outermost element


If you have read this far please leave a like and share your thoughts in the comment section

Happy Coding

Top comments (0)