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.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.