Event Bubbling and Event Capturing in Javascript

Most of us use event handlers in javascripts be it onclick, onmousedown or any other random event handlers.

Behind the scene, how does javascript deal with them. Lets see.

I will go through some examples which will make it easier for you to understand the concept behind event bubbling and event capturing.

Suppose we have a nested div structure.

Event Bubbling: In javascript when an event is triggered on an element inside DOM, the click gets triggered to its next parent until it reaches the topmost element i.e. html.  This is event bubbling. The event bubbles up the DOM. So when we click on the div with id “three” in above code. The onclick event is fired on “three“, “two” and at last “one“. So we will get inside console the output

three

two

one

Now the target element stays the same i.e. div with id “three“. But event pops up to next parent which can be accessed using ‘this‘.

Event Capturing:  Event capturing is just the opposite of event bubbling, the event starts from topmost parent till it reaches the target element. So on clicking the inside most div i.e div#three. We will get the following response.

one

two

three

Now in javascript if you want to specify whether to use event capturing or event bubbling for event handler. We will concentrate on the third parameter inside addEventListener.

addEventListener(“eventName”, EventHandlerfunction(), boolean);

If you specify it as true you will get event capturing for your event handling while if you specify it as false you will get event bubbling.

Thanks for reading this post.