Wednesday, January 13, 2010

How to Add Parameters and Callback Functions to Your JQuery Plugins

Today I am going to expand on the AlertMe plugin I created in the last article.  I will show you how to pass parameters into the plugin, and show you how to create a callback handler for your JQuery plugin.

1.  Parameters can be entered one after the other as part of the function method call e.g. jQuery.fn.AlertMe = function(param1, param2, etc).

But then you have to specify all those parameters when calling the function which is a problem when some of the parameters are optional!. 

Instead what I prefer is creating a function in the plugin which will contain all the parameters.  It also allows setting each parameter to a default value which can later be changed/overridden by the calling client code.

Below is the plugin function, note it has the same name as the main plugin code but has .defaults appended to it.

jQuery.fn.AlertMe.defaults = { 
    alertText: 'AlertMe default text', 
    onAlert: function(alertText) { } 
};

The alertText line has a default set of ‘AlertMe default text’ which will be displayed in the alert box.

And onAlert is a function that allows the client to specify a function that will run when the alert box is shown.

2. Below is the full code for the AlertMe plugin.  As before I placed this code in a file called ‘jquery.AlertMe.js’.

(function($) {
   jQuery.fn.AlertMe = function(options)
   {
        var opts = jQuery.extend({}, jQuery.fn.AlertMe.defaults, options);
        var alertText = opts.alertText;

        function doAlert()
        { 
            alert( alertText );

            // Callback Handler to allow client to run some code when the alert is shown
            if (typeof opts.onAlert == 'function') {
                var callbackAlertText = alertText + ' and then changed by doAlert function callback';
                opts.onAlert.call(this, callbackAlertText);
            }
        }

        return this.each(function() {
            doAlert();
        });
    };

    // plugin defaults
    jQuery.fn.AlertMe.defaults = {
        alertText: 'AlertMe default text',
        onAlert: function(alertText) { }
    };
})(jQuery);

And below is the client html code.

<html>
    <head>
        <script src="jquery-1.3.2.js" type="text/javascript"></script>
        <script src="jquery.AlertMe.js" type="text/javascript"></script>

        <script type="text/javascript">
            $(document).ready(function()
            { 
                var myoptions = {
                    alertText: 'AlertMe changed by client',

                    onAlert: function(alertText) {
                        alert(alertText);
                    }
                }

                $("div").AlertMe(myoptions);
            });
        </script>
    </head>

    <body>
        <h1>Test</h1>

        <div></div>
    </body>
</html>

The main part of the above code is the part shown below:

var myoptions = { 
    alertText: 'AlertMe changed by client', 

    onAlert: function(alertText) { 
        alert(alertText); 
    } 
}

This is where we can change the default parameter values and setup our functions to handle the callback’s provided in the plugin.

3. When you run this code in a web browser a couple of alert boxes will be shown.

The first alert box will say: ‘AlertMe changed by client’.  This is because I set the alertText option.  If I had not set the alertText option the default message of ‘AlertMe default text’ would have been shown.

The second alert box will say:
                  ‘AlertMe changed by client and then changed by doAlert function callback’. 

The second alert box says this because the client has subscribed to the onAlert callback function and inside the plugin when the alert is shown the text returned by the onAlert function is changed which for this demo helps us see that the callback is working.

Wednesday, January 6, 2010

Create Your First JQuery Plugin

This article will show you how to create a simple JQuery plugin.

1. To create a jQuery plugin you should:

  • Name the script file as jquery.YourPluginName.js e.g. jquery.AlertMe.js.
  • Your function must end with a semi-colon.
  • You should use this.each as it produces compatible code.
  • You should not use $ within the plugin unless it is aliased, you should use jQuery instead.
  • Variables should be initialised using the var keyword.

2. Below is a very simple jQuery plugin.

(function($) {
    jQuery.fn.AlertMe = function() {
        return this.each(function() {
            alert(“AlertMe”);
        });
    };
})(jQuery);

3. Using a function within a JQuery plugin.  Below i’ve added a doAlert() function.

(function($) {
    jQuery.fn.AlertMe = function()
    {
        function doAlert()
        { 
            alert(“AlertMe”);
        }

        return this.each(function() {
            doAlert();
        });
    };
})(jQuery);

4. Using variables within a JQuery plugin.  Variables should be initialised using the var keyword.

(function($) {
    jQuery.fn.AlertMe = function()
   {
        var alertText = “AlertMe”;

        function doAlert()
        { 
            alert( alertText );
        }

        return this.each(function() {
            doAlert();
        });
    };
})(jQuery);

5. Your JQuery plugin can then be called from a web page like this:

Reference the JQuery library and your plugin script files in the <head> section of your page like so:

<script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
<script src="Scripts/jquery.AlertMe.js" type="text/javascript"></script>

And on your web page you can use the plugin like this:

$("div").AlertMe();

A bigger example of using the plugin from a web page:

<html>
    <head>
        <script src="jquery-1.3.2.js" type="text/javascript"></script>
        <script src="jquery.AlertMe.js" type="text/javascript"></script>

        <script type="text/javascript">
            $(document).ready(function() {
                $("div").AlertMe();
            });
        </script>
    </head>

       <body>
        <h1>Alert Me JQuery Web Page Example</h1>
        <div></div>
    </body>
</html>

This will attach the ‘AlertMe’ plugin to every div element on the page.  So for example if you had 2 divs you would see 2 alert boxes displayed.