JavaScript: Event Bubbling And Event Capturing Demystified

Published On: 23 Aug, 2016

What Are JavaScript Events ?

JavaScript events are the interactions that are performed on the web page either by the user or the browser itself. Lots of interactions takes place in-front and behind the scene like the ones mentioned below.

  • When a webpage is downloaded by the browser, it triggers “document ready” event.
  • When user clicks on any element, “click” event is triggered.
  • When user hovers over some element, “mousein”, “mouseover” and “mouseout” events are triggered.

Since the browser keeps triggering so many events to respond our interest, in order to make use of these events, we need to bind some functions or methods to them. These functions are called as event callback functions.

Today, modern browsers provide wrapper methods attached directly to DOM objects which can be used to bind callback events. One of them is “document.addEventListener”. Let’s take a look at its syntax and usage.


// Syntax of document.addEventListener method.
domElement.addEventListener(eventName, eventCallback, eventCaptureFlag);

var clickHandler = function(event) {
  // Below code prints the element where we actually clicked.
  console.log(event.target);

  /**
   * Below code prints the element
     whose event callback was called
     on account of CLICK event.
   * In this case, it always prints "document" element
     as the event is bound to "document".
   */
  console.log(event.currentTarget);
};

// Example: Binding CLICK event callback to document node.
document.addEventListener('click', clickHandler, false);

Event Bubbling is the de-facto behavior of any event. If we need to alter it, we need handle it in the callback function (which we’ll study later in this lesson).
Event Capturing can be controlled by the third parameter in “document.addEventListener” method.

As we now have the understanding about using this method, it’s time we learn event bubbling and capturing.

What Is Event Bubbling In JavaScript ?

Event Bubbling is an event propagation mechanism in JavaScript where the event bubbles up like that of the water. Right from the element that triggered the event till the root of the DOM tree i.e. “document” node, event bubbles. Now along this event bubble chain, if any element has corresponding event callback function registered, it’ll get called.

Let’s take a look at the below example. Remember what event.currentTarget returns, right ? If not, please scroll up a little and study the code example. We’ll use event.currentTarget to demonstrate event bubbling behavior.


<html>
  <body>
    <div>
      <a id="anchorElem" href="javascript:void(0);">Hyperlink</a>
    </div>
    <script type="text/javascript">
      var clickHandler = function(event) {
        console.log(event.currentTarget);
      };

      document.onclick = clickHandler;
      document.getElementById('anchorElem').onclick = clickHandler;
    </script>
  </body>
</html>

Here are the observations from the above code:-

  1. When clicked on some element other than the anchor tag, event.currentTarget prints “document” node. This is because bubbling takes place from clicked element upto “document” node, but along this chain, there is a “click” event handler bound only to the “document” node. Hence, this is the only handler that gets called.
  2. When clicked on anchor element, event.currentTarget prints that “anchor” node followed by “document” node. This is because, bubbling takes place from this anchor element right up to the “document” node. But, since this time, anchor element too has “click” event handler bound, it gets called first, followed by that of “document” node.

Stopping Event Bubbling In JavaScript

By now, we know how event bubbles. But sometimes, we need to stop this behavior to avoid certain circumstances. The event object provides us a method called “stopPropagation” using which, we can stop event from bubbling up. Let’s take a look at below code to understand how this can be done.


<html>
  <body>
    <div id="divElem">
      <a id="anchorElem" href="javascript:void(0);">Hyperlink</a>
    </div>
    <script type="text/javascript">
      var clickHandler = function(event) {
        console.log(event.currentTarget);
        event.stopPropagation(); /* This stops event bubbling */
      };

      document.onclick = clickHandler;
      document.getElementById('anchorElem').onclick = clickHandler;
    </script>
  </body>
</html>

Thus, event bubbling works along the DOM hierarchy and one can stop this behavior according to their needs.

What Is Event Capturing In JavaScript ?

Event Capturing is an event propagation mechanism in JavaScript where the event sinks down from “document” node to the child elements. During this event capture phase, start point is “document” node and end point is the element upon which we acted. Similar to Event Bubbling, along this event capturing chain, if any element has corresponding event callback function registered, it’ll get called.

Let’s take a look at the below example. Remember how to set an event to capture, right ? It’s by passing third parameter as true to “document.addEventListener” method.


<html>
  <body>
    <div id="divElem">
      <a id="anchorElem" href="javascript:void(0);">Hyperlink</a>
    </div>
    <script type="text/javascript">
      var clickHandler = function(event) {
        console.log(event.currentTarget);
      };

      document.addEventListener('click', clickHandler, true);
      document.getElementById('anchorElem').addEventListener('click', clickHandler, true);
    </script>
  </body>
</html>

Here are the observations from the above code:-

  1. When clicked on some element other than the anchor tag, event.currentTarget prints “document” node. This is because capturing takes place from “document” node to the clicked element, but along this chain, there is a “click” event handler bound only to the “document” node. Hence, this is the only handler that gets called.
  2. When clicked on anchor element, event.currentTarget prints “document” node, followed by “anchor” node. This is because, event capturing takes place from “document” node to anchor element. But, since this time, anchor element too has “click” event handler bound, it gets called too.

Thus, event capturing works along the DOM hierarchy.

Bugs In DOM Event Implementation

Now we know how event propagation works along the DOM chain. You don’t believe me when I say that there are some browser implementation bugs w.r.t. “addEventListener” method and event propagation behaviors which breaks entire understanding about event propagation. This scenario occurs only when elements in DOM hierarchy are attached with both event bubble and capture callbacks.

Reason is “addEventListener” method keeps on pushing callbacks into a stack irrespective of whether it was meant for bubbling or capturing. So, the event execution order is merely dependent upon the order in which they were attached.

However there is an exception. If both parent and child elements have both event bubble and capture callbacks attached and if user interacted with child element, then parent element always obey those older rules of event bubbling and capturing i.e. capture first, then bubble.

Play with below example to understand this concept a little more.

Well. That’s all about event bubbling, event capturing.. If you’ve any questions/concerns, you can directly email me. Happy learning.

Like this blog ? Share it on your favourite social network.
Search powered by Google

Didn’t find what you were looking for? Try here.

Template Monster

Where you can search over 26K+ Premium Templates.

Now, get flat 10% discount by using “b3fbdxkv49mosrt59dsh0dx29” promo-code.

Email NewsLetter

By subscribing, you’ll get access to latest blogs and other resources. Also, whenever there is any new content addition here, you’ll receive those updates directly to your inbox.

NOTE: I’m a strict antispammer. So you don’t have to worry about spams.

This website is designed by keeping modern browsers in mind. Never mind about legacy browsers. It’s high time we upgrade ourselves.

The website and its contents are created, edited and maintained solely by me (Santosh K Shetty). No one else shall possess any kind of resources unless explicitely mentioned.

Some of the Creative Credit goes to FreePik.

Copyright © from Jun 2014 to May 2018

Table  Of  Contents
On this page,