Wednesday 20 August 2014

Javascript event capturing and bubbling

JavaScript uses two models for event delegation, capturing and bubbling. If you go back in old days, Netscape said that event on parent will take place first and Microsoft said that event on target element will take first. The W3C model combines both capturing and bubbling by saying that an event first makes its way downwards visiting captures i.e parent to target child and then bubbles back visiting non captures. Lets explore further

What is event capturing in javascript ?

In this event model the event is executed in top to bottom order. Always keep in mind that only those events will be fired which has been registered for capturing phase. Use addEventListener with last argument to true is only the way to catch the event at capturing. There are events which don’t bubble, but can be captured. For example,onfocus/onblur. Capturing is rarely used in production environment.
capturing elem.addEventListener( type, handler, phase )
phase = true The handler is set on the capturing phase.
phase = false The handler is set on the bubbling phase.
Lets take an example. Below code shows an html markup of three nested divs
 
<div id="div1">div1
    <div id="div2">div2
        <div id="div3">div3

        </div>
    </div>
</div>

Now we will be using javascript to add on click event to these div's and enable the capturing phase.
 
var divs = document.getElementsByTagName('div')
for(var i=0; i<divs.length; i++) {
  divs[i].addEventListener("click", clickHandler, true)
}

Click on the any of the div's to see the event capturing in action
div1
div2
div3

What is event Bubbling in javascript ?

In this event model the event is executed in bottom to top order. Always keep in mind that only those events will be fired which has been registered for bubbling phase. Use addEventListener with last argument to false is only the way to catch the event at bubbling. Bubbling approach is most commonly used by developers. The deepest element clicked is often known as target element.

elem.addEventListener( type, handler, false)





Now we will be using javascript to add on click event to these div's and enable the capturing phase.
 
var divs = document.getElementsByTagName('div')
for(var i=0; i<divs.length; i++) {
  divs[i].addEventListener("click", clickHandler, false)
}

Click on the any of the div's to see the event bubbling in action
div1
div2
div3

How to stop event bubbling in javascript ?

You can stop bubbling if you don't want event to propagate to its parent.

For W3C-compliant browsers:
    event.stopPropagation()
For IE<9:
    event.cancelBubble = true



No comments:

Post a Comment