Event Capturing and Bubbling in JavaScript

The DOM has two approaches for object to sense events: first is top down approach and second is bottom up approach. Top down approach is called event capturing whereas bottom up is known as event bubbling.

Let’s start with example where you have one html which contains <div>, <p> under <div>, and <input> under <p>

By doing this you will have below ready code

Event Capturing

To understand what is event capturing add event listener to document, div, p, and input, also create functions for each listener. By doing this you will have below code

addEventListener() function have two mandatory parameters “event” and “function” and one optional parameter “useCapture”.

useCapture has two possible values “true” and “false”. If “true” is set, then the event handler will execute in the capturing phase

So as written code if we click on button then output will be as below

ECOutput

In this case even though we are clicking button, it is calling document first and button at last. As written in introduction Event Capturing is like Top Down approach, that is why it is calling click event of document first and button at last in sequence.

Event Capturing

Event Bubbling

Event bubbling is bottom up approach, so sequence of calling event is as below

Event Bubbling

In this case, click event of button will be called first and document at last in sequence. In addEventListener() function if “false” is set for useCapture parameter, then the event handler will execute in the bubbling phase.

To achieve this, we are using same example as event capturing, and code for it will be as below.

Here we are passing “false” as “useCapture” parameter in addEventListener(), this will allow you change event calling flow in bottom up approach.

Output for above code will be

EBOutput

Yatendrasinh Joddha
I am a software engineer currently living in Gandhinagar, India. My interest is in web and software development. I am also interested in sharing my knowledge with people.

I have expertise in asp.net and related Microsoft technologies, with JavaScript frameworks and libraries like JQuery, KnockOut.js,and AngularJS.
Yatendrasinh Joddha on FacebookYatendrasinh Joddha on GithubYatendrasinh Joddha on LinkedinYatendrasinh Joddha on TwitterYatendrasinh Joddha on Wordpress

3 Replies to “Event Capturing and Bubbling in JavaScript”

Leave a Reply

Top
%d bloggers like this: