Generalized Event Handling in JavaScript
By Alexander Hildyard
These days it's unusual to find a Web site that doesn't use client-side scripting to process events presented by a browser's document object model (DOM) as an end user interacts with its pages. JavaScript, with its cross-browser compatibility, has long been the language of choice.
But as a rule, event-based scripts do not mix and match. While you have the choice of writing either highly targeted scripts or generalized scripts, either approach presents its own problems.
A targeted (intrusive, or minimal reuse) script tends to catch events at the lowest level -- that of the element to which that script refers. This guarantees that the script will get to process the events it wants to process. However, it also means that the implementation of the script is no longer abstracted from the element tag to which it refers. It's also extremely redundant and can greatly inflate the size of the resulting HTML page, which may have many elements that exploit a common event handler.
A generalized (nonintrusive, or maximal reuse) script tends to catch events at the highest level -- that of the window or document. This makes it easy for a Web developer to use at least one third-party script without needing to know much about how it works. But it makes it difficult to deploy multiple, event-based, third-party scripts within the same page.
In this article I'll present a single event-handler interface that gives you the precision of targeted scripting along with the flexibility of generalized scripting.