Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

How to Create a Custom jQuery Plugin

Learn how to create and customize your own jQuery plugin.


advertisement

jQuery is a powerful library which makes writing JavaScript code much easier. One of its main features is the possibility of extending default functionality with custom plugins. In this article, you will learn how to create your own jQuery plugin.

Basic Plugin Structure

A simple plugin is created by using the following code:

$.fn.helloWorld = function() {

        // Plugin code goes here
       // In this case, it sets the text of the element(s) to Hello World
        this.each( function() {
            $(this).text("Hello World!");
        });

}


The plugin name in this example is helloWorld. You can change it to whatever you want. Also, a plugin can be run on multiple DOM elements, so we've used the each() function, which loops trough those DOM elements.

Now, we need to make plugin variables and functions available only inside the plugin by creating a closure:

(function($) {


}(jQuery)); 

When the plugin content is added, the code looks like this:

(function($) {

   // This variable is available only inside this plugin
   var text = "Hello World";

    $.fn.helloWorld = function() {

        this.each( function() {
            $(this).text(text);
        });

    }

}(jQuery)); 

The closure is used for protecting the $ alias. Since many JavaScript libraries use $ sign, a conflict could arise between libraries, which could break your plugin. Also, the closure enables us to have private functions and variables.

If you would like to use this plugin, you would write:

$("h2").helloWorld();

A plugin can also have one or more parameters:

 (function($) {

    $.fn.helloWorld = function(my_text) {

        this.each( function() {
            $(this).text(my_text);
        });

    }

}(jQuery)); 

The plugin would be used like this:

$("h2").helloWorld("My text goes here."); 

jQuery plugins can also have private functions, which are available only inside the plugin. Here is a simple example with the private function that handles debugging:

 (function($) {

    $.fn.helloWorld = function(my_text) {
       debug(this);

        return this.each( function() {
            $(this).text(my_text);
        });
    }

    // Private function for debugging.
    function debug( obj ) {
        if ( window.console && window.console.log ) {
            window.console.log("The following text was added:" + my_text);
        }
    };

}(jQuery)); 

It is a good practice to save the plugin as a separate file and minify it (the plugin file name would be helloWorld.min.js). It is also great if you keep the version that is not minified when distributing the plugin package.

Plugin Options

A jQuery plugin can be customized by accepting options. The idea is to have default option values and to override only those that the plugin user has changed. This is done by passing the options as a plugin parameter and then calling the $.extend function:

 (function($) {

   // This variable is available only inside this plugin
   var text = "Hello World";

    $.fn.helloWorld = function(options) {

        // Plugin options default values
        var settings = $.extend({
            color: "red",
            backgroundColor: "white"
        }, options );

        return this.each( function() {
            $(this).text(text);
            $(this).css("color", settings.color);
            $(this).css("background", settings.backgroundColor);
        });

    }

}(jQuery)); 

The plugin options are now in place. If we call the plugin without the options:

$("h2").helloWorld();

The default option values would be used. In this case, the text color would be red and the background would be white. However, if we call the plugin and specify the options:

$("h2").helloWorld({
   color: "black"
});

The default option value for color would be overridden by the custom value, so the text color would be black.

Customizability

Your custom jQuery plugin should be as customizable as possible. There are a few things to implement in order to achieve that. If your plugin creates DOM elements, then you should have a possibility to add an id or a class to those elements. For example:

(function($) {

   // This variable is available only inside this plugin
   var text = "Hello World";

    $.fn.helloWorld = function(options) {

        // Plugin options default values
        var settings = $.extend({
            class: "active",
            id: "hello_world_container"
        }, options );

        return this.each( function() {
            $(this).text(text);
            $(this).attr("class", settings.class);
            $(this).attr("id", settings.id);
        });

    }

}(jQuery)); 

This way you could easily change the way the plugin looks.

It is also important to make the plugin support callback functions. Callback function is a function that is usually called after an event occurred. Callback functions are passed as plugin options:

(function($) {

   // This variable is available only inside this plugin
   var text = "Hello World";

    $.fn.helloWorld = function(options) {

        // Plugin options default values
        var settings = $.extend({
            class: "active",
            id: "hello_world_container",
            onTextAdd: function() {} // Callback function is empty by default
        }, options );

        return this.each( function() {
            $(this).text(text);
            $(this).attr("class", settings.class);
            $(this).attr("id", settings.id);

             // The text has been added
            // Callback function is called at this point
            settings.onTextAdd.call();
        });

    }

}(jQuery)); 

Now, we will define a callback function and call the plugin:

$("h2").helloWorld({
   onTextAdd: function() {
      alert("The text has been added.");
   }
});

Next Steps

There are a lot of jQuery plugins available online now. Before starting to create your own plugin, check whether a plugin with the same functionality already exists by visiting the jQuery plugin registry or searching for it on Google.



   
Vojislav is a web developer, designer and entrepreneur, based in Belgrade, Serbia. He has been working as a freelancer for more than 6 years, having completed more than 50 projects for clients from all over the worlds, specializing in designing and developing personal portfolios and e-commerce websites using Laravel PHP framework and WordPress content management system. Right now, he works as a full-time senior web developer in a company from Copenhagen.
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date