Practical Use of JavaScript Event Bubbling
An Universal Event Handler

Since addEventListener() is not supported by current version of Internet Explorer, let's use a workaround that utilizes the familar method of assigning event handle.

Here's a code that traverses a html document and assigns the specified event handler (eventHandlerFunctionToBeCalled).

function propagateEventHandler(currentElement, 
eventHandlerFunctionToBeCalled) { if (currentElement) { var tagName=currentElement.tagName; // save the original handler to be nice if (currentElement[eventName]) { // Use object so that we can support more than one event if (!currentElement.originalEventHandler) currentElement.originalEventHandler=new Object(); currentElement.originalEventHandler[eventName]=currentElement[eventName]; } // Any element with this class name will be ignored if (currentElement.className=="noEventCapture") { return; } currentElement[eventName]=eventHandlerFunctionToBeCalled; // Traverse the DOM tree and assign the event handler to its descendants var i=0; var currentElementChild=currentElement.childNodes[i]; while (currentElementChild) { propagateEventTrap(currentElementChild,
eventName, eventHandlerFunctionToBeCalled); i++; currentElementChild=currentElement.childNodes[i]; } } }

The code is used on this page like this (placed on the bottom of the page so the all elements are elready on the page when the function is called):

propagateEventHandler(document.body, "onclick", onClickHandler);

Click anywhere on this page and you will see every onclick event being captured and propagated from the source element and to its ancestor (the propagation is shown in the textfield below). The Clear button is not captured because I had specified "noEventCapture" (an arbitrary identifier to signar the propagation to stop) as its class name. In real application, you might not want to blindly target everything, but a specific form for example. Or you can target only specific kind of element like <table> rows or <div>s belonging to particular class, by expanding on this check:

if (currentElement.className=="noEventCapture") { return; }

Here are some elements that you can try clicking:

Click here
Click here


The parameter eventHandlerFunctionToBeCalled can be any function that you write. In this example, I simply print out the information about the event, such as who sent the event and the id of the sender, etc. Then redirected the output to the text-field below. View source to see the function.

So with this one simple call, we have redirected all onclick event to one single function without having to manually assign an onclick or onchange to many elements. Imagine how practical it can be for instant form validation, for instance.