Unobtrusive JavaScript Tutorial
May 28th, 2007 | Published in Blog, Web Design
Getting Your Markup Ready
The first step to using Unobtrusive JavaScript is to remove all of the inline JavaScript from your markup. This does not mean that you can never use JavaScript inline in a document. What it does mean is that you may choose to add it as an option and not out of necessity.
In order to add behaviors to elements later you are going to have to find them in the document. This means that you may have to add “id”, “class”, or “rel” attributes to the elements that you are trying to find. Keep in mind that it is good practice to keep the use of these attributes semantic.
Find Elements That You Want to Add Behaviors To
In order to add behavoirs to the desired elements you need to first parse the document and find all of the elements that you are looking for. For example let say you want to add some behavior to every element on a page with the class name of “button” Below is an example of how to find elements by class name. This example uses the getElementByClassName function from the Prototype Library.
function findButtons() {
var checks=document.getElementsByClassName("button");
for (var i=0; i < checks.length; i++)
{
// .. found the elements
}
}
Adding the JavaScript Behavior
Now lets create the function that will add an on click behavior to an element.
function findButtons() {
var checks=document.getElementsByClassName("button");
for (var i=0; i < checks.length; i++)
{
checks[i].onclick=function() {
//.. do something cool
return false;
}
}
}
Making the Script Run On Load
The final step is to make the findButtons() function run when the page is loaded. To do this we have to add one more line of code to our script.
window.onload=findButtons;
Now your JavaScript should be working and unobtrusive.