Bubbling is a good thing...and no I'm not talking about the fact that it might help you to locate a turtle. Javascript events bubble from the source element outward. This gives you a couple of important benefits when attaching event handlers to elements:
- reduced resource usage - one global handler instead of a handler on each element
- simpler wiring with dynamic content - instead of adding handlers to new elements inserted into the page, the parent element already has the lone handler
The following example shows some code where a div element with an id of "overlay-entries" contains a number of, well, overlay entries in which each overlay entry has an checkbox element that allows that overlay to be shown or hidden. Instead of wiring up a handler for the "change" event for each checkbox we can merely catch the events as they bubble to the containing div with the id "overlay-entries." With prototype Event objects are normalized to make sure that the .element() method returns the element that the event actually originated on. In my situation it is enough to check that the event fired on a checkbox to allow the corresponding event to fire: