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.

Why Use Unobtrusive Javascript

May 10th, 2007  |  Published in Blog, Web Design

One of the Best things about CSS is that you keep your content and style separate from each other. Keeping the style separate from the content of a page allows you to keep the markup intelligible. The benefit of this is that it makes everyone’s job in the production line easier. The developer does not have to worry about adding style to the content and the designer can keep making tweaks to the design without altering the content on the page. If you already have a large site up and want to change the appearance of a few elements this is a huge benefit.

How this all relates to unobtrusive JavaScript is that the same principals of CSS can be applied to JavaScript via keeping the behavior of a web page separated from the content.