Capture VS Bubble
MR.H
Posted on March 17, 2023
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')
})
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
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})
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
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
Posted on March 17, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.