Friday, 8 April 2016

Event bubbling in javascript

Event bubbling and capturing

Event bubbling and capturing are two ways of event propagation in the HTML DOM API, when an event occurs in an element inside another element, and both elements have registered a handle for that event. The event propagation mode determines in which order the elements receive the event.
With bubbling, the event is first captured and handled by the innermost element and then propagated to outer elements.
With capturing, the event is first captured by the outermost element and propagated to the inner elements.
Capturing is also called "trickling", which helps remember the propagation order:
trickle down, bubble up
Back in the old days, Netscape advocated event capturing, while Microsoft promoted event bubbling. Both are part of the W3C Document Object Model Events standard (2000).

Here is the html:

<div id="div1" class="element1">The blue square <div id="div2" class="element2"> The red square </div> </div>

Here is the css:

.element1{
  background-color: blue;
  height: 200px;
  width: 200px;
  position: relative;
  top: 2px;
  left: 20px;
}
.element2{
  background-color: red;
  height: 100px;
  width: 100px;
  position: relative;
  top: 40px;
  left: 50px;
}

Here is the javascript:

/* Event bubbling. */
/* The html used in this js file is given in the html file. */
var div1 = document.getElementById('div1');
var div2 = document.getElementById('div2');
var clickHandler = function divClickHandler(event){
console.log(this.id);
};
div1.addEventListener('click', clickHandler, false);//bubbling
div2.addEventListener('click', clickHandler, false);//bubbling
/* 
The false as the thrid argument in the method call above causes the bubbling. First event is handled
by div2 and then it it is bubbled to its parent div1. If we want it the other way round i.e., we wnat div1
 to handle the event first and then bubble it to div2 then we need to set the boolean value to true as the
 thrid argument in the call to addEventListener().
 */
div1.addEventListener('click', clickHandler, true);//capturing
div2.addEventListener('click', clickHandler, true);//capturing

/* If we wnat the event to be handled by the parent but not by the child then we can stop the propagation of 
the event by using method stopPropgagation() as shown below. In this case the parent will handle the event 
and stop further propagation of the event to the child. 
*/
var div1 = document.getElementById('div1');
var div2 = document.getElementById('div2');
var clickHandler = function divClickHandler(event){
console.log(this.id);
    event.stopPropagation();
    /* 
    If we want to prevent the default action when something is clicked then we include the followin one line of   code also. 
    */
    event.preventDefault();
};
div1.addEventListener('click', clickHandler, true);//capturing
div2.addEventListener('click', clickHandler, true);//capturing

No comments:

Post a Comment