Add to Favorites

Unobtrusive Javascript

The term "Unobtrusive Javascript" refers to the technique of separating out your javascript from the html presentation of your web page. It is a useful technique that allows you to manage large portions of your website utilizing more centralized javascript.

The common way javascript has been used in the past, you would see it strewn throughout the html source code on events for different form fields or anchors. It would be commonplace to see something like:

<input type="text" onclick="open_calendar(this)" class="date_picker" />

Using the onclick is quick and easy, but what if you had hundreds of these date fields used throughout the site, and you now needed to provide a format argument to your open_calendar function ( or some other syntactical/functionality change ). You would be stuck using a find/replace for many files or even doing some manual labor going through and adjusting appropriately.

Using the unobtrusive javascript technique, you would set the onclick event for this input field through javascript that can be placed into one single file. Instead you would leave your input without javascript:

<input type="text" class="date_picker" />

You would have a file set the onclick event. For the purposes of this example, I will be using jQuery to set this onclick event. In a separate javascript file that you include in your header of the html source, you would define your unobtrusive javascript. For example:

$(document).ready(function(){
$('input.date_picker').bind('click', function (){
open_calendar(this);
});
});

When the page loads, this javascript will go through all the objects that have the class "date_picker" and set an onclick event for them to call open_calendar. In this method, if you needed to make a global change to how this function is called or even call a different function, you would only need to modify the one javascript file used by all your pages.

This method can also be useful for applying zebra tables to all tables used on your site without needing to go back and change every one of your pages.

As you can see, this can be a powerful technique and save you lots of time.

Comments

Be the first to leave a comment on this post.

Leave a comment

To leave a comment, please log in / sign up