JavaScript Event Handling

Event Bubbling and Event Capturing

As a JavaScript developer It’s very important to understand the event and how their handler works under hood. So Today I am going to talk about Event Bubbling and Event Capturing in JavaScript.

How Event’s Work?

Before starting this let’s see how’s you DOM is structured in the browser.

Here above as we can see window is the root element of our browsing page. Below that we have our document tree and after html ,body etc. So this is the basic general tree of out page.

Now, Let’s suppose you clicked on the buttonOne on the page. For this click one click will be fire form the javascript and that event will go down to that element through the path of window and all of their parent elements as we can see in the image.

And when it find that element on the tree , it looks for and event handler and if it is there then fire that handler and then come back to the root element.

When event come to the element it’s called as Event capturing and when it go up to the root after handling the event is called as the Event bubbling.

Now, Suppose we have a event handler like

event.addEventListner('click' , callback , true)

Last argument is for

True : capture event on Event Capturing Cycle.

False : capture event on Event Event Bubble cycle.

If we are listening for that element then it’s okey to capture event on any cycle. But suppose if you are listening this event to it’s parent element then that event will check all the elements of that part and and find the particular element for that even and fire the callback for that element and event.

Event Propagation

When that event is moving in the path that process is event propagation. You can stop the propagation if you want to with event.stopPropagation.

Like suppose you have a link structure like this

div
p
ul
li
a

So suppose you click on the “a” and you have this function

var ul = document.querySelector(‘ul’);
ul.addEventListener(‘click’ , doSomething , true);
function doSomething(event) {
event.stopPropagation();
}

This kind of function can be useful in many JavaScript process such as parallax animation and other things.

GOODBYE !!!

Hope you learn something new from this blog and hope that this will help you in the future or at any time :). So If you find this helpful share this. Happy Learning

“Share your knowledge. It is a way to achieve immortality.”
by Dalai Lama XIV