Monday, December 29, 2008

Javascript Event Bubbling with Prototype

Update: After I wrote this post I remembered that change events don't bubble in IE6 for select elements and thus likely don't bubble for check boxes either. After an investigation I found out that no - they don't bubble. So this code won't work correctly for IE 6 which still commands a 20% + share of the market. Please STOP IE6 NOW...and on with the post.

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: