An event capturing is an event propagation principle in HTML DOM API.

When there is an element inside another element and both have registered for an event, the handler of the outer most element is executed first (when the event occurs) followed by the propagation to the inner element. This principle is called the event capturing. The event capturing is an opposite effect to the event bubbling. If there are more than one outer elements handling the same event, the event is "passed" from the outer most element till it reaches the inner-most element.

NOTE: This propagation principle was initiated by Netscape browser in older days. IE older than version 9 do not support this feature.

Syntax for events capturing

addEventListener(event, function, useCapture);

where:

  • event – Event to be handled.
  • function – Handler for the event. It is executed on event occurrence.
  • useCapture – This should be a true in order to make the event work in capturing mode. A false make the event bubbling to occur.

Example of events capturing

The element which triggered the event is called as event.target or event.srcElement (in IE). Irrespective of the element to which event is passed to, the target/srcElement remained the same. But argument this changes every time to that element which triggered the handler.

The capturing can be stopped from propagating down to the inner elements by setting a Boolean event.cancelBubble or the event.stopPropagation() method.

Syntax for events capturing propagation canceling

element.onclick = function(event){
    event = event || window.event;
    //Works in W3C standard
    if(event.stopPropagation()){
        event.stopPropagation();
    }else{
        //Works for IE 
        event.cancelBubble = true;
    }
}

 

NOTE: The event flow specified by the DOM 2 events recognizes 3 phases: event capturing phase, event target, event bubbling phase. When an event triggers, event capturing occurs first, then event hits the actual target, and finally event bubbling occurs. IE9, Opera, Firefox, Chrome, Safari all support DOM event flow.  IE8 and older do not.

 

›› go to examples ››