jQuery Plugin Tutorial

Welcome to my tutorial on how to make your first jQuery plugin. If you are ready to make a plugin I’m assuming you have already used a few plugins, written a few jQuery scripts and now have a killer script that you want to share with the world. The great thing about jQuery plugins is that you can set controls for a user to modfy the script without having to dig in to your code. Obviously, if your script is just a few lines long, there isn’t really any need to create a plugin as they are generally for larger scripts with a selection of variables that would need to be changed.

This tutorial will show you the basic building blocks of a jQuery plugin and apply it to a simple script. I have decided to keep the code simple so as not to defer from the focus of making the plugin itself. In practice, this wouldn’t need it’s own plugin, but using it is an easy way to demonstrate the basics. I will show you how to define the function and give it a name, set the options for the user and implement the plugin in to an HTML document.

In this tutorial we are going to make an HTML document and set the color, background, height and width CSS properties of a div using a jQuery plugin. First we need to write the HTML. Open up your favourite text editor and place the following markup in a new file.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
		<title>jQuery plugin tutorial</title>
	</head>
	<body>
		<div>
			<p>The color, background, height and width CSS properties are set by my jQuery plugin</p>
		</div>
	</body>
</html>

Now that we have the basic page we can begin to add the magic and start working on our plugin. The method that I have chosen is to write the script as I normally would to make sure everything works properly first before constructing the plugin. It is entirely up to you how you go about it but I just find it easier when it comes to debugging.

jQuery Plugin

As with all jQuery scripts we need to first call the jQuery library. I have recently started linking to the google hosted library rather than downloading it directly to my server. This ensures that I’ll always have the latest version without having to continually download it. The google hosted library will also be in the cache of most computers as most people will have visited google at some point. The main advantage of this is that it will reduce loading times. To do this we put the following code in the head section of our page.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>

We’ve now got our building blocks in place so we can start writing our code to set the CSS properties. After we call the jQuery library in the head section we write another script tag and let it know that we don’t want the script to activate until the document is loaded.

<script type="text/javascript">
$(document).ready(function(){

});
</script>

Next we write the code to set the CSS properties of our div. First we call the div, as there is only one div on the page we can use $(div) rather than calling a specific class or id.

Then we need to set the CSS properties so our code looks like this:

$(div).css({
	color : 'white',
	background : 'blue',
	width : 400,
	height : 100,
});

Our HTML document should now look like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
		<title>jQuery plugin tutorial</title>
		<script type="text/javascript">
			$(document).ready(function(){
				$(div).css({
					color : 'white',
					background : 'blue',
					width : 400,
					height : 100,
				});
			});
		</script>
	</head>
	<body>
		<div>
			<p>The color, background, height and width CSS properties are set by my jQuery plugin</p>
		</div>
	</body>
</html>

We can now save the page and the div should look like this in the browser:

Now that we have our HTML page and our jQuery script we can start building our plugin. First open a new file in your text editor and save it as jQuery.firstplugin.js. The jQuery documentation suggests that all plugins should be named jquery.plugin_name.js, it won’t affect the plugin if it isn’t named like this but if they are courteous enough to supply this wonderful framework for free it’s only right to follow their suggestions.

The first part of the plugin is to define the function and give it a name that will be used in our HTML page. We will also set the variable ‘options’ to control the function.

$.fn.makeDiv = function(options) {//set up the function and give it a name

};

I have called this plugin makeDiv but you can name it whatever you like. The next step in the plugin is to set the default values for our controls in a variable. In this example we are going to set the default CSS properties that the user of the plugin can then set themselves.

settings = $.extend({//set the default values for the controls
	color : 'white',
	background : 'blue',
	width : 400,
	height : 100,
}, options);

The .extend method allows us to alter the default values when we call the makeDiv function in our HTML page. Now that we have set our variables we have to tell the plugin function what to do with them. To do this we need to use the code from our HTML page and make a few tweaks to it so that it works within the plugin. First we need to make the code affect the element that we select when we call the makeDiv function. In order to do this we change $(‘div’) to $(this). We then need to change the values that we have to those in the settings variable. To do this, rather than having values, we use settings.value. The code for the plugin should now look like this.

$(this).css({//set the css properties of the selected element
	color : settings.color,
	background: settings.background,
	width : settings.width,
	height : settings.height
});

We now put all this code together and have created our first jQuery plugin. The full plugin code is shown below:

$.fn.makeDiv = function(options) {//set up the function and give it a name
	settings = $.extend({//set the default values for the options
		color : 'white',
		background : 'blue',
		width : 400,
		height : 100,
	}, options);
	$(this).css({//set the css properties of the selected element
		color : settings.color,
		background: settings.background,
		width : settings.width,
		height : settings.height
	});
};

The next step is to test the plugin and have a play with the controls. As I said at the beginning I assume that if your are ready to build a plugin then you have more than likely used other plugins and implemented them in your pages. For those that haven’t I will now quickly take you through the basic process of using a plugin. First we need to open up the HTML page and remove the jQuery script that we put in earlier. We then need to call the plugin using a script tag in the same way that we call the jQuery library.

<script type="text/javascript" src="jquery.firstplugin.js"></script>

Next we need to select the div and use the makeDiv function on this div.

<script>
$(document).ready(function(){
	$('div').makeDiv();
});
</script>

Our page should now look as it did before when we tested the code with a blue div that has white text, a width of 400 and a height of 100.

Now we can see the magic of the plugin at work. Start playing with the variables and how you call the function. Below is an example to show the versatility of even this very simple plugin. The example below changes the dimensions of the div using a click event.

 <script>
$(document).ready(function(){
	$('div').click(function(){
		$('div').makeDiv({
			background: 'green',
			color: 'black',
			height: 200,
			width: 50
		});
	});
});
</script>

Well that is all for this tutorial, you now know the basics of making a jQuery plugin. Thanks for reading, I hope you have enjoyed this tutorial. If you have enjoyed it, please leave a comment. I also look forward to seeing and using all the interesting plugins that you are all now able to produce.

Download and Demo

11 Comments on "jQuery Plugin Tutorial"

  1. Lenny says:

    You need to return the original object from the plugin.

    return $(this).css({...});

  2. Hi Lenny,

    You are correct, if the author wanted to support jQuery Chain-ability (which he should) then he should have returned it. However, this plugin will work fine, but as I said not support Chain-ability.

  3. Thanks for sharing such nice technical information here with proper code. I will try to execute it. It is nice to post here. I like this site very much.

  4. booby says:

    Thanks you very much for your Tutorial. Great Tutorial.

  5. Igor Romero says:

    Right. there should be a return statement in the end. Also, i noticed that $ was used initially. I think alias should be instated. hence,

    (function($){
    $.fn.makeDiv = function(options) {

    }
    })(jQuery);

  6. thanks for sharing….

  7. Rami Toma says:

    ok i think this tutorial was the best one i ever saw and it was right to the point not like the others with useless information. thanks for sharing

  8. Amol Bhavsar says:

    Hi Mark,

    I have developed my first jQuery plugin using your tutorial.

    Thanks for sharing such invaluable information.

    I am really thankful to you and I appreciate your efforts.

    Keep people helping with your philanthropic nature.

    Thanks,
    Amol

  9. Jesse says:

    Thanks for this tutorial. I found it easy to follow and was successful in making my first jquery plugin!
    One technical note: the first example (where it says “Our HTML document should now look like this”) does not actually run.
    Two reasons: Jquery is not included in the example, and $(div) needs single quotes to be $(‘div’).
    thanks

  10. Good for beginners. I think jquery in its very nature is very easy to understand…

  11. Annie392 says:

    As image-manipulation software becomes easier to use and harder to detect, the problem of tampering has spread far beyond such celebrity “corrections.” While fudged paparazzi moments do little more than embarrass editors, there are far more important C and sometimes illegal C fakes to catch. Many tools have been developped to expose these touchups, like Photoshopped Image Killer, which leverages internal statictial models of images to do such work.

Got something to say? Go for it!