Theme images by Storman. Powered by Blogger.

Wednesday 28 September 2016

Event bubbling and capturing in JavaScript



 In the HTML DOM API event bubbling and capturing are two ways to determine event propagation or which element is going to receive handler first for given event.

       when an event occurs in an child element and both(parent and child) elements are register a handler for that event. The event propagation mode determines in which order the elements receive the event.

Bubbling:

The event is first captured and handled by the child element and then propagated to parent elements.

Example:

<!DOCTYPE HTML>
<html>
<body>
<div class="div1"> block 1  
    <div class="div2">block 2
        <div class="div3">block 3</div>
    </div>
</div>
</body>
</html>

From above given code click on div3 will trigger event  first on the child element 3 , then on the element 2, and the last will be element 1.

Capturing:

The event is first captured by the parent element and propagated to the child elements.

Example :

<!DOCTYPE HTML>
<html>
<body>
<div class="div1">block 1
    <div class="div2">block 2
        <div class="div3">block 3</div>
    </div>
</div>
</body>
</html>

From above given code click on div will trigger event  first on the parent element 1 , then on the element 2, and the last will be element 3.

Enable event capturing on element :

element.addEventListener("click", doSomething, useCapture);

useCapture = true
The handler is set for the capturing .
useCapture = false
The handler is set for the bubbling.

Example :

<!DOCTYPE HTML>
<html>
<body>
<div id="div1"> block 1  
    <div id="div2">block 2
        <div id="div3">block 3</div>
    </div>
</div>
</body>
</html>

var element = document.querySelector("#div3");

// set capturing
element.addEventListener("click", doneClick, true);

// set bubbling
element.addEventListener("click", doneClick, false);

Stop event capturing/bubbling :

W3C standard:
event.stopPropagation()

IE:
event.cancelBubble=true

Example:

function doneClick(e) {
    e.stopPropagation();
}

Trick to remember the propagation order:

Trickle(capture) down, bubble up

Note:
  • There are events which don’t bubble, but can be captured. For      example, onfocus/onblur.
  • In IE<9 Events are only bubble.


0 on: "Event bubbling and capturing in JavaScript"