An event bubbling is a way of handling events in HTML DOM API.
When there is an element inside another element and both have registered for an event, the handler of the inner most element will be executed first (when the event occurs). Afterwards the event is propagated to the outer element</i>. This behaviour is called event bubbling. If there are more than one outer element handling the same event, the event will be bubbled from inner most element all the wat to the most outer one, till it reaches the document’s root element.
Syntax for events bubbling
addEventListener(event, function, useCapture);
where:
- event – Event to be handled.
- function – Handler for the event. It is executed on event occurrence.
- useCapture – A Boolean which determines if the event is bubble or capture. Widely used value is false, which ensures a bubbling propagation over capturing in order to support the cross-browser functionality.
The example below has two nested div elements with a paragraph. When the onclick event occurs on the paragraph, its event is triggered first, and then the handler of the first div with respect to the paragraph will be triggered. After that the event on the outer div will be triggered as well. The event is said to bubble out from the inner most element.
Example of events bubbling
The inner most element which triggered the event is called event.target or event.srcElement (in IE). Irrespective of the element to which event is bubbled to, the target/srcElement is the same. But argument this changes every time to that element which triggered the handler.
The bubbling effect may be stopped and canceled in the event handler by setting a Boolean event.cancelBubble or a event.stopPropagation() method.
Syntax for events bubbling 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;
}
}
Comments
No comments have been made yet.
Please login to leave a comment. Login now