Chain JavaScript Events

In JavaScript there can be only one JavaScript onload event handler. This is a somewhat an issue if you have all sort of third party libraries that want to run some piece of JavaScript code when the page finishes loading. You can use the YUI! Event library add and chain event listeners to a DOM element, but adding another resource dependency to you application might not always be the right answer. I recently had to chain some onload event handlers for a simple script I was writing and I didn’t want to require any additional files. Here is my poor man’s version of a JavaScript event chain gang.

With code like this you can guarantee that the old even handler code will run before your new code.

Technorati Tags: , , , , ,

Multiscreen Dialogs and the JFileChooser »
« JavaOne 2007 Conference Notes
 
Related Posts
Recent Posts
 

4 Comments so far

  1. Ed Eliot on June 20th, 2007

    Simon Willison’s addLoadEvent which uses closures is well worth a look: http://simonwillison.net/2004/May/26/addLoadEvent/

  2. TechKnow on June 21st, 2007

    @Ed - Thanks for the tip. That was helpful. The above code is, in my mind, the simplest possible way to chain events. The next step would be to pass functions as parameters, much like Simon’s describes. But perhaps the best option is just to use some commonly maintained library. Once again, thanks!

  3. Alex G on June 21st, 2007

    Am I missing something here? Would addEventListener/attachEvent not work here?

  4. TechKnow on June 23rd, 2007

    @Alex - I think I am just being stubborn, :). I wanted to stay away from having to check if the browser supports either addEventListener, attachEvent, or neither. So I thought the simplest hack that would work would be something like the above. I agree with you though, for ‘production’ type of work I would use some supported JavaScript library that abstract the use of addEventListener/attachEvent.

Leave a reply