jQuery Plugins

Jakob Jenkov
Last update: 2014-09-23

It is possible to implement plugins for JQuery. Plugins are independent units of functionality that can be reused between applications. For instance, a plugin could be as little as a single function, or consists of several functions and objects (data).

JQuery has a big list of plugins which you can download and use. You can find the list here:

http://plugins.jquery.com/


In this text I will show you how to write your own plugins.

The Plugin JavaScript File

All of your plugin JavaScript code should be contained in a single, independent file. You should include this file after you include the JQuery JavaScript file. For instance:

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

<script type="text/javascript"
     src="/jQuery.myJQueryPlugin.js">
</script>

Single Function Plugins

If your plugin can be contained in a single JavaScript function, you can create a single function plugin. Here is how you do that:

jQuery.myPlugin = function() {
    alert("Hello World, plugin");
}

You can now call the function directly on the JQuery object, like this:

jQuery.myPlugin();

Or by using the $ object (a shortcut for the jQuery object), like this:

$.myPlugin();

Multi-function Plugins

If you need to group multiple functions together in a plugin, you can do so by adding them to a JavaScript object, and set that JavaScript object on the JQuery object. Here is how that looks:

jQuery.myPlugin2 = {

    function1 : function() {
        alert("function1");
    }
    ,
    function2 : function() {
        alert("function2");
    }
};

You can now call these two functions in your plugin like this:

jQuery.myPlugin2.function1();
jQuery.myPlugin2.function2();

Or you can use the $ shortcut object, like this:

$.myPlugin2.function1();
$.myPlugin2.function2();

Working on Selections

If your plugin needs to modify a JQuery selection (a set of selected HTML elements), you have to use a slightly different approach. You will have to add your function to the fn object of the jQuery object. Here is an example:

jQuery.fn.modify = function() {
    this.each(function() {
       $(this).css("background-color", "#ff00ff");
    });

    return this;
}

To call this function, you would write this:

$("h2").modify();

First all h2 elements are selected. Then the modify() function is called on the selected elements.

Notice how the modify() function is added to the fn object of the jQuery object. This is necessary for it to be able to work on JQuery selections.

Also notice how the each() function is called on this inside the modify() function. The reason for this is that a JQuery selection can contain multiple elements. Thus, to apply the effect of your function to all elements in the selection, you must iterate the selection and apply the effect to each element.

One more thing to pay attention to is, that the reference called this inside the modify() function, refers to the collection of selected elements. Inside the each() function, however, the this reference points to the current element being iterated. Thus, the two this references do not point to the same objects.

Finally, notice how the modify() function returns this. This means that modify() returns the selected elements. This is handy if you want to chain JQuery calls after the modify() function call. Here is an example:

$("h2").modify().attr("align", "left");

Since JQuery users are used to being able to chain method calls like this, it is a good idea to make your plugin behave as users expect.

Subselector Plugins

You can also create custom selector plugins for JQuery. A custom selector plugin is a selector that filters selected elements. You add a selector plugin like this:

jQuery.extend(jQuery.expr[':'], {

   'align' : function(element, index, matches, set) {
        // return true or false
   }

});

The first parameter to the jQuery.extend function, jQuery.expr[':'], tells the extend method that this selector is prefixed with a colon. Colon is the commonly used prefix for selector plugins.

The second parameter to the jQuery.extend function is a JavaScript object with a single property called align. The name of this property is the name of the subselector. The value of this property is a filter function which is called for every selected element. If the subselector function determines the element should be included in the final selection set, the function should return true. If not, the function should return false.

Before looking at the implementation of the function, let's see how to use the above subselector:

$("h2:align(right)");

The selector expression in this example selects all h2 elements in the page, and then passes each element to the function set in the align property, of the JavaScript object passed to the jQuery.extend() function, as shown in the code sample earlier. If the function returns true, the specific element is kept in the selection set. If the function returns false, the element is excluded from the selection set.

Now let's look at the implementation of the filter function:

jQuery.extend(jQuery.expr[':'], {

   'align' : function(element, index, matches, set) {
    
        if( jQuery(element).attr("align") == matches[3] ) {
        return true;
        }

        return false;
    
   }

});

This filter function includes all elements that have an align attribute matching the value passed as parameter to the subselector in the selection expression. In the usage example shown earlier (h2:align(right) ), the filter function would include all elements with an align attribute with the value right.

The element parameter passed to the filter function is the selected element which the function should determine whether to include in the selection set or not.

The index parameter contains the index of the element within the selection set.

The matches parameter is an array containing the result of the regular expression used to parse the selector expression containing your subselector. The matches[3] element of the array, contains the parameter passed to your subselector, if any. In the example above (h2:align(right) ), matches[3] would contain the value right.

The set parameter passed to the filter function contains the complete set of elements matched before this function call. That is, the set of elements matching the first part of the selector. It is not a set of elements accepted by the filter function before this specific filter function call.

Plugin Code Conventions

You plugin should adhere to a set of conventions which users of JQuery plugins are used to expect from plugins. I'll go through them here.

Your plugin cannot assume that it can use the $ function. In some applications the $ is used for other JavaScript functions than JQuery. Therefore your plugin should always call the jQuery function instead of using the $() function. The two functions behave exactly the same, so this is no problem. It is just a thing to remember.

You plugin JavaScript file should be named using the pattern

jquery.pluginName.js

where pluginName is the name of your plugin.

Method definitions should be ended with a semicolon (;), so your plugin works even with JavaScript compression.

Parameters to plugin functions should have sensible defaults, in case they are not provided by the user of your plugin.

Jakob Jenkov

Featured Videos

Java ConcurrentMap + ConcurrentHashMap

Java Generics

Java ForkJoinPool

P2P Networks Introduction

















Close TOC
All Tutorial Trails
All Trails
Table of contents (TOC) for this tutorial trail
Trail TOC
Table of contents (TOC) for this tutorial
Page TOC
Previous tutorial in this tutorial trail
Previous
Next tutorial in this tutorial trail
Next