Unobtrusive JavaScript is easy

Unobtrusive JavaScript is easy, I said it. It is easy and useful. Hard coding a call to a JavaScript function in a link isn't hard to do. It isn't even hard to change if you have to. But what if that link was repeated across 10 pages, 100 pages, 1000 pages? That is a lot of changes that could have been avoided with unobtrusive JavaScript.

Lets say you have a link on your page that hides a div. You could put this code in your page

<a href="#" onclick="hideDiv()">Hide Div</a>

or this code

<a href="#" class="hideDiv">Hide Div</a>

They don't seem too different do they? Well they are, for many reasons. The first link is obtrusive the second is unobtrusive. More importantly link #2 is more versatile, it can perform the same function as link #1 but also be styled. If you don't need this link anymore just set the display to none in your CSS and problem solved. So lets look at how to make this unobtrusive.

How does it work? Line #2 takes all the a tags and puts them in an array named allLinks. Line #3 starts a loop that goes through the allLinks array created on line #2. Line #4 is an if statement checking to see if the link has a class name of hideDiv. Line#5 ties it all together, if a link has been clicked with class name of hideDiv the function on line #6 is called.

The last thing needed is to add the function to the window on load function. I recommend using the technique I talk about here.

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment