This content was originally published at Kyan’s blog at http://kyan.com/blog/2008/9/26/unobtrusive-scripting-with-jquery, but is no longer available at that location. Reproduced here with permission.

Unobtrusive scripting with jQuery

Here at Kyan we love unobtrusive scripting: scripting that adds on to the top of an existing web page and extends it to add functionality and interaction niceness.

We often use a Javascript library called jQuery to help us add scripting to our sites, and it’s got a nice extension mechanism. Let’s have a look at writing a small jQuery plugin to add a simple piece of functionality to our site: a print link after a news story.

A print link only works when Javascript is turned on, so for users without scripting they get a dead link. This isn’t a particularly nice experience, but we can do better. Let’s assume that the markup we want is:

<button>Print this page</button>

We can easily add this to the bottom of our news story (<div id="news_story">…</div>) using jQuery:

function addPrintButton() {
	$('<button>Print this page</button>').appendTo('#news_story');
}

This is fairly simple to understand: nearly all statements in jQuery are a selection or creation (in this case our button) followed by one of more actions (in this case appending it to the element with an id of news_story). We also need to add the print functionality, but this can simply be chained into the same statement:

function addPrintButton() {
	$('<button>Print this page</button>')
		.click(function(){window.print();})
		.appendTo('#news_story');
}

How do we call this? jQuery provides a simple mechanism for calling functions on page load with the $(function(){}) syntax:

$(function(){
	addPrintButton();
});
function addPrintButton() {
	$('<button>Print this page</button>')
		.click(function(){window.print();})
		.appendTo('#news_story');
}

Bingo! A print button on every news story. But there’s one remaining trick we can use to make this more flexible. As I said earlier, a typical jQuery statement starts with a selector. Wouldn’t it be good if we could add a print button to any required element on the page? Luckily jQuery provides just such a mechanism. If we extend jQuery itself with our function then we can use it in the same way as the library functions:

$(function(){
	$('#news_story').addPrintButton();
});
jQuery.fn.addPrintButton = function() {
	return this.each(function(){
		$('<button>Print this page</button>')
			.click(function(){window.print();})
			.appendTo(this);
	});
}

jQuery.fn is the collection of functions that jQuery knows how to address. We simply add our new function to that collection, and make sure that we pass the selection out of our code so that we can chain more functions onto the end if needed.

So there you go: a simple jQuery plugin in 5 minutes.