unobtrusive javascript
Aug 13, 2005 · 3 minute readLots of talk around at the moment about unobtrusive javascript on the usual websites and discussion lists. However alot of people, maybe outside the inner circles, are still finding old school examples of inline code on out of date pages.
So here’s my tuppence. I guess the more websites that post new, up to date, examples and reasoning the better?
The premise is pretty simple. In the same way as controlling formating with tables and having everything being mixed up in one .htm file is frowned upon as simply being too much work – dealing with lots of inline snippets of javascript raises the same problems. Namely being time consuming to update and maintain.
The solution is to keep ALL your javascript in separate .js files, and that includes removing things like href="javascript:"
or onclick=
. The first question is therefor how – when I started looking down this route I found a simple answer hard to come by, having to look at more complex examples and reverse engineer them.
The following is the method I’m using at the moment. It may have issues I’m unaware – if your a javascript guru let me know. The examples are from the fluidflash page on this site, see it in action at www.morethanseven.net/fluidflash
We first I set up an initialisation function:
function init() {
if (!document.getElementById) return false;
liquid = document.getElementById("iNavLiquid");
liquid.onclick = liquidChangeClass;
}
This sets the onclick event on the element with the id iNavLiquid
that will trigger the function liquidChangeClass
. Next we define that function:
function changeClass( targetId, newClass ) {
if (document.getElementById){
target = document.getElementById( targetId );
target.className = newClass;
}
}
function liquidChangeClass() {
changeClass("iBody","liquid");
}
The specifics aren’t too important to this example but you can see the liquidChangeClass
function which is triggered by the onclick event handler.
And finally we need to trigger the init
function when the page loads. Their are lots of ways of doing this which is probably a conversation for another time – I used a schedule
function from themaninblue.com which you can find below:
function schedule(objectID, functionCall, iteration) {
if (iteration == null){
iteration = 0;
}
if (objectID == "window") {
var oldonload = window.onload;
if (typeof window.onload != "function") {
window.onload = functionCall;
} else {
window.onload = function() {
oldonload();
functionCall();
}
}
} else if (document.getElementById(objectID)) {
functionCall();
} else if (iteration < 300) {
setTimeout(function(){schedule(objectID,
functionCall, iteration + 1)}, 10);
}
return true;
}
schedule("window", init);
So their we have it, hopefully a simple enough example of how to move to unobtrusive javascript. As most of this is generic and used all the time it’s far simpler that it first appears.