<form onclick="handleClick()"> <fieldset> <input id="bubbleexample" type="text" /> </fieldset> </form>
Notice that our event handler has been set on the form and not on the text box itself. When the text box is clicked, the event generated will first be called on the text box itself. Then it will move up to the fieldset. Next it will hit the form element. It will continue to affect each ancestor element until it reaches the root element (document). This is called event bubbling.
Notice also that we are handling that event on the form element and not on the the text box itself. This is called event delegation.
You may, at this point, be asking yourself: what's the advantage of this technique? In the case above where we are only looking at a single event, there is no advantage. However, as the number of event handlers on your page grows, you can see significant performance increase both in terms of processing time and memory use. A complete discussion as to the exact reasons why is beyond the scope of this tutorial; but the important aspects are:
- The event handler only has to be applied to one element (reduces processing time)
- Only one copy of the event handler will reside in memory (reduces memory consumption)
In this example, I've applied event handlers using event delegation, and included metrics regarding processing time differences between using delegation and adding an event handler to each item individually.
There is, of course, a caveat to using event delegation: events you had no intention to handle will likely need to be handled gracefully by your handlers. Notice on line 12, of the example, the event handler checks to make sure it is not acting on the parent container; only the elements within that container. Obviously, as the DOM becomes more complicated beneath your chosen delegator element, so too will become the handler that must check what element it is being called on.
That said, the benefits do outweigh this potential pitfall. As you'll notice the code for the handler itself merely determines which element it was called on, checks that the element qualifies for action, and passes the element to another function which performs the actual action. This is good architecture; as the code to determine what to do with a particular event grows and multiple paths become possible, your code will be much easier to read and work with when you separate the actual action from the event handling.
So there you have it; a very brief introduction to using event delegation and its advantage over the more traditional paradigm.