IT Insights Blog
Follow SkylineFollow Skyline On TwitterFollow Skyline On Linked InSkyline's RSS FeedSign Up For Skyline's Email Newsletter 

Creating Your Own jQuery Plugins
January 5, 2012


Dan Lorenz, Software Engineer


jQuery is a powerful JavaScript library that can help you write client-side code quickly and efficiently, while being cross-browser friendly.  (It’s even somewhat fun to code in!)  The jQuery team has created the framework in a way that allows developers to write their own plugins for other developers to use.  This post will take you through the steps to create your own plugin.

You should start by creating a new JavaScript (text) file.  Normally, you name it something like “jquery.myname.js”.  There are other JavaScript libraries out there, so you’ll want to denote that your plugin requires jQuery.

There are two ways to create your own jQuery Plugins.  The first way simply creates a jQuery function that a consumer can call.  The second way makes use of a jQuery method called “widget” from the jQuery UI library that lets you do some more powerful things, but is a bit more complex.  Let’s start with the simple way…

First, you will define the name of your method.  You do so with the following syntax:

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

}
})(jQuery);

The first part guarantees that the “$” is the shortcut used to represent jQuery.  Other framework libraries use “$” as their shortcut, and this approach makes sure that “$” means jQuery in your plugin. The second part allows the consumers of your plugin to call your function like this:

$(“#someId”).NameOfYourMethod();

The “options” part is optional and allows consumers to pass some customization parameters into your code.  A good plugin exposes many different parameters to get the effect that the developer wants, making the plugin more user-friendly.

Now you want to start coding your plugin.  The first step should be to setup the default parameters you want.  You can do so easily with the “extend” method:

var defaults =
{
myParm1: 5,
myParm2: 4
};
options = $.extend(defaults, options);

This code will push any variable not defined on the options from the defaults.  For example, let’s say that the developer called your code as such:

$(“#someId”).NameOfYourMethod({ myParm1: 10 });

In your code, myParm1 would be 10 and myParm2 would be 4.  You should also keep a reference to this if you have other function calls other than this main one.  In this case, this refers to the element with id “someId”.

var topElement = $(this);

From here, you start coding whatever you need to code.  There are a few things you should keep in mind.  First, when looking for parent elements, make sure you don’t search above $(this).  You might end up modifying HTML that was not intended for your plugin to change.  You can do so by the following style:

$(“#someOtherId”).closest(“ul”, $(topElement)).find(“> li”);

Second, make sure you expose meaningful option parameters to make your plugin more dynamic.  As you code your plugin, these parameters will become clearer.  Also, give them good names so other developers know what they are changing.  Third, try to break up your plugin into smaller functions.  You can put all the code into the top method, but you will have a more difficult time maintaining it.  You can declare your own functions like this:

function MyFunction(topElement, options, someData) {

};

Then you would call this code like this:

MyFunction(topElement, options, ‘test’);

Finally, you should allow developers to get the full code and “minified” version of your code.  Minified JavaScript is code that runs through a tool that removes all the white-space, comments, and renames variables to make the code much smaller.  Humans have an extremely difficult time reading it, but the compiler doesn’t have that problem.  Users of the script will have to download less, speeding up the download and the host will not have to use as much bandwidth, saving money.  You can also compress the file, like a .zip file, but this is not recommended.  While you may save more bandwidth, the user’s experience will be slower.  You can minify your JavaScript here.

Here is some example code that will add a button and display a message to the user:

(function ($) {
        jQuery.fn.ShowMessage = function (options) {
            var defaults =
            {
                message: 'Hello!',
                buttonText: 'Click Me!'
            };

            options = $.extend(defaults, options);
            var topElement = $(this);
            $(topElement).append('<input type="button" value="' + options.buttonText + '" />')

            $(topElement).find('input').click(function () {
                alert(options.message);
            });
        }
    })(jQuery);

The second way is similar, but a little more complex.  Instead of directly creating your own function, you call the widget method.  The widget method takes multiple parameters which include the options, create function, destroy function, and setOption method. The options allows you to define the parameters like in the simple way, except you won’t have to call extend.  The “_create” method is the code that gets called when someone calls the function. This is where the majority of your code will go.  The destroy method is called when someone is trying to remove your plugin code.   In this method, you should restore the HTML back to its original state before your plugin was run.  Sometimes, this may be very difficult to achieve. 

Finally, the _setOption method allows consumers to change options after the fact.  You may or may not need to do this.  If you choose to allow it, then you will have to write code to support changing option parameters on the fly.  Methods with an “_” in front denote private methods.  They cannot be called outside of that plugin.  Here is an example that duplicates the simple code, while providing ways to destroy and update the options:

(function ($) {
        $.widget("ui.ShowMessage",
        {
            options:
            {
                message: 'Hello!',
                buttonText: 'Click Me!'
            },

            _create: function () {
                var topElement = this.element;
                var options = this.options;

                $(topElement).append('<input type="button" value="' + options.buttonText + '" />')

                $(topElement).find('input').click(function () {
                    alert(options.message);
                });
            },

            destroy: function () {
                var topElement = this.element;
                topElement.remove();
            },

            _setOption: function (option, value) {
                $.Widget.prototype._setOption.apply(this, arguments);
                var topElement = this.element;
                switch (option) {
                    case "message":
                        this.options.message = value;
                        break;
                    case "buttonText":
                        this.options.buttonText = value;
                        $(topElement).find('input').val(value);
                        break;
                }
            }

        });
    })(jQuery);

In your code, you call the various methods as such:

$("#someId").ShowMessage({ message: 'Test', buttonText: 'Hi' });
$("#someId").ShowMessage("destroy");
$("#someId").ShowMessage("option", "message", "test2");
$("#someId").ShowMessage("option", "buttonText", "test2");

 

A Proud Partner In The New North
Microsoft Gold Certified Partner