Simon Willison’s Weblog


Javascript Mojo

5th November 2003

Stuart Langridge has released a couple of very neat new Javascript experiments. sorttable makes any data table on a page “sortable” by clicking the table headers. I’ve seen this effect used to demonstrate Microsoft’s proprietary “behaviors” technology but Stuart’s solution has the advantage of being standards compliant and working across different browsers. Best of all, it follows the principles of inobtrusive DHTML and hooks in to the markup using only a class attribute.

Stuart’s second experiment, JavaScript Event Sheets, is even more interesting. It tackles the problem of attaching events to page elements. The most common way of doing this is with inline attributes, but these require adding behavioural (rather than structural) code to your markup and can lead to additional maintenance costs further down the road. A better alternative is to use the DOM to dynamically add events, which works fine but means tightly coupling the structure of the document to the Javascript that sets up the events. Stuart’s solution is to abstract the logic that attaches events to elements out to a separate file, called a Javascript Event Sheet. This uses CSS style syntax (partially handled by my getElementsBySelector function) to specify how events attached to different elements should be handled. Stuart demonstrates the idea with a common image rollover:

img.rollover {
  mouseover: rollover_handler;
  mouseout: rollout_handler;

Stuart’s blog entries concerning the two new experiments are here and JavaScript Event Sheets.

This is Javascript Mojo by Simon Willison, posted on 5th November 2003.

Next: easytoggle and debugging in Safari

Previous: Web design and usability guidelines

Previously hosted at