Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Event bubbling in JavaScript

Suggested Videos
Part 37 - Assigning event handlers in JavaScript using DOM object property
Part 38 - addeventlistener and removeeventlistener in JavaScript
Part 39 - JavaScript event object



What is event bubbling 
Let us understand this with an example. HTML elements can be nested inside each other. For example a button element can be nested inside a span element and the span element in turn can be nested inside a div element as shown below. 



javascript event bubbling

Notice that we have onclick attribute specified for all the 3 elements.

<html>
<head>
    <style type="text/css">
        .styleClass
        {
            display: table-cell;
            border: 1px solid black;
            padding: 20px;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="styleClass" onclick="alert('Div click handler')">
        DIV element
        <span class="styleClass" onclick="alert('Span click handler')">
        Span element
            <input type="button" value="Click me" onclick="alert('Button click handler')" />
        </span>
    </div>
</body>
</html>

A click on the button, causes a click event to be fired on the button. The button click event handler method handles the event. The click event then bubbles up to the button element parent (span element), which is handled by the span element event handler method. The click event then bubbles up to the span element parent (div element). This is called event bubbling.

Notice that if you click on the <span> element, it's event handler and it's parent(<div>) element event handler are called. If you click on the <div> element, just the <div> element event handler method is called. So, the event bubbling process starts with the element that triggered the event and then bubbles up to the containing elements in the hierarchy.

The following example is similar to the one above, except we removed the onclick attribute from button and span elements. Because of event bubbling, when you click on the button or the span element, the event gets handled by the div element handler.

<html>
<head>
    <style type="text/css">
        .styleClass
        {
            display: table-cell;
            border: 1px solid black;
            padding: 20px;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="styleClass"
      onclick="alert('Click event handled by DIV element')">DIV element
        <span class="styleClass">Span element
            <input type="button" value="Click me"/>
        </span>
    </div>
</body>
</html>

When the event gets bubbled, the keyword this references the current element to which the event is bubbled. In the example below, we are using "this" keyword to reference the current div element and change it's border color. When you click on the innermost <div> element, all the 3 <div> elements border get changed due to event bubbling.

javascript event bubbling explained

<html>
<head>
    <style type="text/css">
        .divStyle
        {
            display: table-cell;
            border: 5px solid black;
            padding: 20px;
            text-align: center;
        }
    </style>
</head>
<body>
    <div id="DIV1" class="divStyle">
        DIV 1
        <div id="DIV2" class="divStyle">
            DIV 2
            <div id="DIV3" class="divStyle">
                DIV 3
            </div>
        </div>
    </div>
    <script type="text/javascript">
        var divElements = document.getElementsByTagName('div');

        for (var i = 0; i < divElements.length; i++)
        {
            divElements[i].onclick = function ()
            {
                this.style.borderColor = "red";
                alert(this.getAttribute("id") + " backgound changed");
            }
        }
    </script>
</body>
</html>

Stopping event bubbling : If you don't want the event to be bubbled up, you can stop it. 

With Internet Explorer 8 and earlier versions
event.cancelBubble = true

With Internet Explorer 9 (and later versions) & all the other browsers
event.stopPropagation()

In the example below we have stopped event bubbling. So, when you click on DIV 1, only DIV 1 border colour is changed.

<html>
<head>
    <style type="text/css">
        .divStyle
        {
            display: table-cell;
            border: 5px solid black;
            padding: 20px;
            text-align: center;
        }
    </style>
</head>
<body>
    <div id="DIV1" class="divStyle">
        DIV 1
        <div id="DIV2" class="divStyle">
            DIV 2
            <div id="DIV3" class="divStyle">
                DIV 3
            </div>
        </div>
    </div>
    <script type="text/javascript">
        var divElements = document.getElementsByTagName('div');

        for (var i = 0; i < divElements.length; i++)
        {
            divElements[i].onclick = function (event)
            {
                event = event || window.event;

                if (event.stopPropagation)
                {
                    event.stopPropagation();
                } else
                {
                    event.cancelBubble = true;
                }

                this.style.borderColor = "red";
                alert(this.getAttribute("id") + " backgound changed");
            }
        }
    </script>
</body>
</html>

javascript event bubbling stop

JavaScript tutorial

2 comments:

  1. You are the greatest teacher if someone like me with no prior knowledge of programming can understand up to this level then i most confess you are the greatest of all

    ReplyDelete
  2. thanks...code sample + video really helps us who are visual learners...

    ReplyDelete

It would be great if you can help share these free resources