DEV Community

Nurofsun
Nurofsun

Posted on • Updated on

Get to Know Event Bubbling and Capturing in JavaScript

For you who has learned about event,you may want to have deep understanding about it, have you learn about event bubbling and capturing? if not, this is the right article for you.

<div id="parent">
  <button id="children">Click me</button>
</div>
Enter fullscreen mode Exit fullscreen mode

Event Bubbling

let parent = document.querySelector('#parent'),
    children = document.querySelector('#children');

parent.addEventListener('click', function() { 
    alert('Parent clicked')
});

children.addEventListener('click', function() { 
    alert('Children clicked')
})
Enter fullscreen mode Exit fullscreen mode

Consider to simple HTML markup and few lines of JS code above, once you click button with id children two alert will show up. First alert with text Children clicked followed by another alert with text Parent clicked.

Wait a minute? Who are you? said a parent element.
I'm your children. said the children element.

What does it mean? The concept of bubbling The way of events are up.

Event Capturing

let parent = document.querySelector('#parent'),
    children = document.querySelector('#children');

parent.addEventListener('click', function() { 
    alert('Parent clicked')
}, { capture: true });
// you can also just put `true` as third argument.

children.addEventListener('click', function() { 
    alert('Children clicked')
})
Enter fullscreen mode Exit fullscreen mode

Keep take attention on HTML markup and JavaScript code above, to make the behavior of event become capturing, you need to set option object capture: true on parent event or you can just put true as third argument.

When you click button with id children the first alert will appear is an alert that attached on parent element (event) which has text Parent clicked and after that alert with text Children clicked will appear.

So, do you get it? Yes, the way of events down.

The Difference Event Bubbling and Capturing

After you test that code I've provide you may get the conclusion of differences of these kind of events, the way of events of both are different.

Event Bubbling is up, and Event capturing is down.

Top comments (0)