At the Forge - Unobtrusive JavaScript

Remove JavaScript event handlers from HTML files using Prototype and Lowpro.

Assigning events in this way has some advantages over using the onclick and related attribute-based event handlers. It lets us define all of our event handlers in a single place—typically at the end of the HTML file. Thus, we have some separation between our HTML and JavaScript.

But, what if we want to go one step further, putting all our JavaScript into a separate file? Listing 3 shows a new version of our HTML file, now called test-3.html. Instead of having the JavaScript at the bottom of the page, I put it in a separate file, called atf-events.js (Listing 4). However, if you try to load this file, you quickly will discover that it doesn't work. We get a JavaScript error upon loading the file (clearly evident and readable if you're using the wonderful Firebug debugger for Firefox), telling us that $('hyperlink') is null.

How can this be? If you look through Listing 3, you still will see an HTML element with an ID of hyperlink. And, we definitely have included the Prototype library, so $() should work. How can it be, then, that $('hyperlink') returns null?

The answer is subtle, but well known to JavaScript programmers: $('hyperlink') is available only after the HTML element with an ID of hyperlink has been loaded. Because our JavaScript file was loaded (in the <head> of the document) before the hyperlink element was defined, JavaScript threw us an error.

One solution to this problem is to load our JavaScript at the end of the file, right before the closing </body> tag. Another possibility is to define all of our event handlers in a function that itself is executed only after the entire document is loaded. In other words, we define a function (set_event_handlers) that defines all of our event handlers. Then, we attach this function to the window.onload event, which executes only after the entire document has been loaded. The code, shown in Listing 5, is exactly the same as Listing 4, except the functionality is wrapped in the set_event_handlers function, which is invoked based on an event.



Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

So interresting...

Arimbourg's picture

Thanks for this article. Clear and so usefull...