So You Want to Write a jQuery Plugin?


If you see yourself repeating the same jQuery code in a couple of pages, it is time to package that into a plugin. In this tutorial we will show you how to get started with jQuery plugin development.

Getting Setup

In your web server’s document root, create a folder called lab. We will create all files here.

In the lab folder, create a simple HTML file called plugin.html. Set the content of the file as follows.

<html>

<head>
<title>jQuery Labs</title>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js">
</script>

<script type="text/javascript">
    $(function(){
    	//jQuery code here
    	
    });
</script>

</head>

<body>
<!-- Body HTML here -->
<p class="c1">Hello World</p>
</body>

</html>

Save the file.

Open a web browser and enter the URL: http://localhost/lab/plugin.html. Make sure that you see the "Hello World" message.

Self Invoking Function

Before we get into plugin development, let’s learn about self invoking functions. This is a JavaScript technique, where a function is called by itself. This is great for functions that initialize things. This eliminates the need for the developers to write extra code to call this function.

Right above the </script> line, add these lines:

(function (msg){
	alert(msg);
}("I got called"));

Save changes. Refresh the browser. You should see the alert dialog.

image

A self invoking function has these syntax elements:

  1. The function may be anonymous or have a name. In the example above, it is anonymous.
  2. The input parameters are supplied within parenthesis right after the end of the function definition (or the last "}").
  3. The whole thing must be wrapped in parenthesis. This is crucial. Without that, you will get a JavaScript compilation error.

Self invoking function has many uses. In the next section, we will see how it plays a role for jQuery plugin development.

Delete the self invoking function before moving to the next section.

Writing a Simple Plugin

Every plugin is a function. This function is added to the prototype of the jQuery object. Recall, how any plugin is called:

$("p1").plugin_func_name(args);

The core function $("p1") returns a jQuery object. Here, plugin_func_name is a property added to the jQuery’s prototype. The value of the property is the plugin function.

Right above the </script> line, add these lines:

(function($){
    $.fn.myPlugin = function() {
        alert("Cool plugin");
    };
}(jQuery));

Here we see a self invoking function. The function is passed the jQuery global object as input. From within the function, we use the symbol $ for the input. Hence, $ is same as the jQuery object. All of this is just to simplify typing (typing $ is easier than jQuery). Using the self invoking function makes sure that the $ sign used here does not conflict with any previously declared variable by the same name ($) by any other toolkit (such as Prototype).

Anyway, the key thing is how we are adding the myPlugin property to the prototype of the jQuery object.

$.fn.myPlugin = function() {
    alert("Cool plugin");
};

Umm… what is this $.fn thing? Shouldn’t it be jQuery.prototype if we are trying to tweak the prototype of the jQuery object? First of all, jQuery and $ are one and the same object. Secondly, the "fn" property is same as the prototype. Somewhere within jQuery code, there is: jQuery.fn = jQuery.prototype. OK, fine. If you want to strictly play by the JavaScript rule, you don’t have to use self invoking functions of $.fn. You could so something like this and things should still work:

jQuery.prototype.myPlugin = function() {
    alert("Cool plugin");
};

But, self invoking function allows you to create private variables and functions. Something you need for complex plugins.

This is perhaps the simplest plugin anyone can develop. Now, we can start using our plugin.

Within the DOM ready handler function, below the line:

//jQuery code here

Add:

$().myPlugin();

Save changes.

Refresh the browser or enter http://localhost/lab/plugin.html. You should see the plugin doing its thing.

image

This is a fully legit plugin. Except it doesn’t do anything that anyone cares about. In the next section, we will change that.

Work on Selected Elements

The core function $() does all the heavy lifting of selecting DOM elements in the page that match the passed selector rule. All a plugin has to do is do something with these elements.

We already know that the each() jQuery function is used to iterate over selected elements. We can use it from our plugin function.

Delete the line:

alert("Cool plugin");

In it’s place, enter the plugin code as shown below.

$.fn.myPlugin = function() {
    this.each(function() {
        this.innerHTML = "Your class is: " + this.className;
    });
};

The "this" keyword within the plugin function points to the jQuery object. Hence, we can call the each() function. Within the iteration handler function, "this" points to the DOM element. Hence, we can use the DOM API and access properties like innerHTML and className.

Change the selector rule from where the plugin function is called.

$(function(){
    //jQuery code here
    $("p").myPlugin();
    	
});

Save changes. Refresh the browser. You will notice that the text of the paragraph changes from "Hello World" to "Your class is: c1".

image

Add another paragraph below the existing one.

<!-- Body HTML here -->
<p class="c1">Hello World</p>
<p class="c2">Hello World</p>

Save changes. Refresh the browser.

image

Review

In this tutorial, we learned the basic structure of writing a jQuery plugin. From this point, you can use the powerful jQuery API to create amazing and cool plugins. For more information on advanced plugin development topics, see this article.

  1. No comments yet.
(will not be published)

*