Unobtrusive javascript is a term used for a certain style of scripting HTML pages that avoids that the scripts ‘get in the way’. For example, javascript fragments scattered throughout the HTML source ‘blocks’ the view of that source in a way, making it harder to read. Or creating a global variable named i. That’s bound to get in the way of other scripts.

We have all by now learned that we should separate content from presentation on our website by placing the content in the HTML document and the presentation in the stylesheet. Websites like CSS Zen Garden have thought us that. The same is true for script code. Mixing it in with our document is not wise. Instead, we should separate it into behaviors that can be applied to the document in a reusable fashion. And that’s where unobtrusive javascript comes in.

Unobtrusive javascript employs a series of techniques and tricks to apply behavior to an HTML document and circumvent traditional problems that used to prevent us from doing so in an unobtrusive fashion. For example, suppose we wanted to attach some behaviour to some HTML element, say attach a LargePicturePopup function to every thumbnail on a page that pops up the large version of the picture when you click on it. Now suppose we already have everything in place in an external .js file. Perfect right? But to attach the function to the HTML element, we have to assign it to the element’s onclick. This is how it was (and still mostly is) done:

<img src="small-image.gif" onclick="return LargePicturePopup('large-picture.gif');" />

But here we are mixing HTML and javascript. Sure it’s only a single function call right? But it’s on every thumbnail on our page! And soon we will start to add more arguments to the function.. or we want to execute the function only in some cases.. and our script code starts to take over the page.

Now a better solution would be to attach an event to the HTML element through script. This can be done from an external script file. We need to lookup the thumbnail in the DOM and then call addEventListener on it to attach our function to it. How hard can that be right? Well as it turns out, not so easy. IE does not support addEventListener for starters. And how do we look up the element? And more tricky, when do we look it up? If our script runs while the element we want to attach to is not even read by the browser yet, what happens then?

This blog talks about these issues and underway tries to answer all questions asked above and some more. I hope you’ll enjoy reading it.