Developing a jQuery plugin

Posted on Saturday, July 26th, 2008

One of the reasons I think jQuery is the best JavaScript library is because of all the plugins available. There are thousands! So, in this article I’ll be demonstrating the ease with which you can develop your own jQuery plugin!

We’re going to create a basic message plugin which fades in when the user clicks on a particular element. It’s not very advanced so it should be easy to follow along even if you’re a beginner.

Right, first we need to setup some HTML to work with, here is our basic document:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
 
	<head>
 
		<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
		<title>A simple jQuery plugin</title>
		<script type="text/javascript" src="jquery.js"></script>
		<script type="text/javascript" src="message.jquery.js"></script>
 
		<style type="text/css">
			body { font-family: "calibri"; font-size: 1em; }
			.message { padding: 10px; margin: 10px; text-align: center; }
		</style>
 
	</head>
 
	<body>
 
		<p>A very interesting paragraph!</p>
 
		<ul>
			<li title="This is the amazing message">Some useful info</li>
			<li>Some more info</li>
			<li>And... some more!</li>
		</ul>
 
	</body>
 
</html>

As you can see, we have a couple of scripts being loaded, some styles defined, a paragraph of text and an unordered list.

"message.jquery.js" is the empty JS file where we will write the plugin.

Before writing the plugin it’s best to figure out how we want it to be called. Doing this before the plugin is made is useful because it allows us to see what properties/capabilities we want before we get started.

This is how we want our new plugin to be called:

$('p').message();

Pretty simple! - We want the plugin to be applied to all paragraph elements.

We’re not done yet though - we also want to pass some properties; we need to define what the message will say and some of it’s style attributes:

$('p').message({
	message: 'You just clicked on a paragraph',
	textColor: 'red',
	backgroundColor: 'yellow',
	border: '2px dashed green'
});

Now that we know how we want it to be called, it will make it much easier to write.

To define a new jQuery plugin is very simple, - jQuery allows you to name your plugin to whatever you want.

jQuery.fn.message = function(options) {
	// All the "STUFF" goes here...
}

We now have a plugin; it doesn’t do anything yet, but it does exist.

Notice that there is one argument for this function called "options". Within this "options" argument all the customisable properties will be defined. There needs to be some default options just encase the user does not specify something. For example if the user does not pass in a "textColor" property then we need it to default to something.

So the first part of our plugin will be the defaultOptions object:

var defaultOptions = {
	message: 'This is a test message',
	backgroundColor: 'green',
	textColor: 'white',
	border: '2px solid yellow'
};

Now we need to loop through that object and find if the user has determined their own options:

for (var i in defaultOptions) {
	if(!options) var options = {};
	if(!options[i]) options[i] = defaultOptions[i];
}

The above loop goes through each property and value of the "options" object (which has been passed as a parameter) and determines whether the user has specified that property - if the user has not then it sets that property to it’s default (defined in the "defaultOptions" object).

Using objects in this situation is better than just passing through lots of parameters like this:

$(’p').message(’red’,'blue’,'hello’,'2px solid white’);

It’s not very readable when you do the above, so using objects with property-value pairs is a much nicer, cleaner and clearer way of doing it.

The user can specify the options object within the parenthesis when the plugin is called or the user can define the object before that:

var myOptions = {
	message: 'You just clicked on a paragraph',
	textColor: 'red',
	backgroundColor: 'yellow',
	border: '2px dashed green'
};
$('p').message(myOptions);

Right… now back to the script - so far, we have the following:

jQuery.fn.message = function(options) {
 
	var defaultOptions = {
		message: 'This is a test message',
		backgroundColor: 'green',
		textColor: 'white',
		border: '2px dotted yellow'
	}
 
	for (var i in defaultOptions) {
		if(!options) var options = [];
		if(!options[i]) options[i] = defaultOptions[i];
	}
 
}

Next we need to define the contents of message. We know what the text will be (specified in options) but we have to create it’s container:

var message = '<div class="message" style="display:none"><p>' + options.message + '</p></div>';

We’ve given the message a class of “message” so that we can style it from within the CSS

Hopefully you will have noticed how we’re accessing the options (options.message. You could also access the message property within the “options” object like this: options['message']

Now we can write what occurs on the click event:

$(this).click(function(){
	// STUFF HERE
});

When using the this keyword within a jQuery plugin you are referring to a single iteration of the element/’s selected. So, in this situation it is attaching the event to the paragraph (remember we called the plugin like this: $('p').message() - so this refers to each iteration of ‘p’. (In this case there is only iteration because there is only one paragraph within the document)

Within the click function we want to remove all previous instances of the message, prepend the message to the body of the document and style the message with the options defined either by the user of those which were previously specified in defaultOptions:

$(this).click(function(){
 
	$('.message').remove();
 
	$('body').prepend(message);
 
	$('.message').css({
		backgroundColor: options.backgroundColor,
		color: options.textColor,
		border: options.border
	}).fadeIn();
 
});

The above chunk of code removes all messages and then prepends the new message to the document. It then applies the CSS and fades the message in.

You can see a DEMO of the plugin here.

If you have a look at the source of that demo then you’ll see that the plugin has been called like this for the list items:

$('li').each(function(){
	$(this).message({
		message: this.title || "You just clicked on a list item"
	});
});

This applies the plugin to all the list items within the page. The only reason I’ve iterated through each one is so I can get at the title attribute of each list item and then pass it in as the message string. The message property has been defined as either the title of the list item or an alternate string. The string ("You just clicked on a list item") will get passed only if the title does not exist for that particular list item. (this OR that - this being prevalent).

I hope this article has been useful to you. If you’re unsure about any aspect of this then please leave a comment/question below. :)

One Response to “Developing a jQuery plugin”

  1. Gravatar #1 :: Thomas Milburn Says:

    I did kind of request this tutorial so thanks James for answering my request and writing another brilliant article.

    I’ll be sure to start creating my own plugins!

Leave a Response

Allowed elements include: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <em> <i> <q cite=""> <strike> <strong>.
Please wrap any multi-line code snippets in the <pre> element. (Characters are automatically escaped this way) - also you can specify the language within the lang attribute, e.g. <pre lang="php">echo 'hello';</pre>. (Available languages: "php", "javascript", "html4strict")