Dapoxetine manufacturer's approved product information from DapPremium you can view video goodrx.com. For France use http://edfromparis.com website to help buy priligy in Paris. GiveUpAlready.com - jQuery: Creating a Plugin
  • Top Authors

    Username Articles Kudos


    Gary Upton-Abbott View Articles 1,477

    Shards View Articles 1,377

    Sr Gregor View Articles 69

    ChaosLight View Articles 22

    I Am View Articles 14

    TheEvilGenius View Articles 9

    eth View Articles 7

    RazoR_ View Articles 6

    LT3 View Articles 6

    Sailor Moon View Articles 6

  • jQuery: Creating a Plugin

    In the last article, we learned about the difference between live() and bind() - and when to use them. In this article we're going to put bind() to use and create our first jQuery plug-in.

    If you use jQuery, you've heard of its plug-ins - easily reusable bits of code that you can call on selectors like any other jQuery method. What you may not realize is how easy it is to write your own plug-ins, making code reuse in your projects easier then ever.

    01: The Set-Up

    In order to create a plug-in, you need an environment that supports one. Create a new folder and inside that folder create two documents:

    • colorize-test.html
    • colorize.jquery.js
    The first file is the file we'll use to test our plug-in, and the second file is the plug-in itself. In the test file, enter the following HTML:
    HTML Code:
        <!DOCTYPE html>
        <html>
        <head>
            <title>My First jQuery Plug-In</title>
            <script src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
            <script src="colorize.jquery.js" />
            <script>
            $(document).ready(function() {
     
                // The DOM is ready, start coding!
     
            });
            </script>
        </head>
        <body>
            <p>Pellentesque habitant morbi .... </p>
            <p>Pellentesque habitant morbi .... </p>
            <p>Pellentesque habitant morbi .... </p>
            <p>Pellentesque habitant morbi .... </p>
            <p>Pellentesque habitant morbi .... </p>
        </body>
        </html>
    Fill the paragraph tags with placeholder text; you can copy a sentence from somewhere and repeat it five times. Notice we've included the jQuery library in the head of our document from the freely provided jQuery CDN. We've also linked our jQuery plug-in to the document, and put a document.ready block below that for when we're ready to use the plug-in.

    The purpose of our plug-in is going to be to change the color of text when clicked. Not very exciting, but the idea is to learn how to create a plug-in, not to create anything special.




    02: Writing the plug-in: Deciding the Interface

    When writing a plug-in, it's often best to first decide on how it will be used. In the majority of cases, this means determining the options since almost all plug-ins are used by calling them in a chainable fashion on a selector. Here's how using our plug-in will look:

    Code:
        $('.selector').colorize({
            colors      :   ['#FF0000','#00FF00','#0000FF']
        });
    We've decided on one option - an array of colors to cycle through when the element is clicked. The item will also cycle back to its original color as part of the programming.

    If the option isn't set then the plug-in will use the default values we assign inside the code.




    03: Plug-In Basics

    When you write a plug-in, jQuery has a namespace they provide for you to attach it ($.fn) so our plug-in gets wrapped in code like this:

    Code:
        $.fn.colorize = function(options) { ... }
    The entire thing gets wrapped in a self-executing function so it will run and attach itself to jQuery. Here's what that looks like:


    Code:
        (function($) {
            $.fn.colorize = function(options) {
                // Plug-In Code Here
            };
        })(jQuery);



    04: Get The Options

    The first thing your plug-in code has to do is handle the passed in options. To do this, you have to set defaults and merge any values the user has set when calling the plug-in. Sounds potentially complex, but it's not.

    Code:
        // Defaults and options
        var defaults = {
            colors      :   ['#FF0000','#00FF00','#0000FF']
        };
        var opts = $.extend({}, defaults, options);
    The preceding code would be dropped in at the start of the colorize function. It sets an array of defaults, then takes it and the options the user has passed in, combining them into the opts array using jQuery $.extend. Any values in the user-given array will <b>over write</b> any values in the defaults array.





    05: Working on Each Element

    It's important to remember that jQuery plug-ins are called on a selector which may return between zero and a LOT of items that match the selector. Within the scope of your colorize function, the special variable 'this' will refer to this jQuery collection. So after we've set up our default, we are going to loop over this collection with the 'each' method.

    Code:
        this.each(function() {
     
            // This code is applied to every element defined by the selector
            // the special variable 'this' is redefined here 
        });
    Within the 'each' loop, the special variable 'this' is redefined automatically as the current DOM element of the jQuery collection. In order to access it as a single jQuery object, we'll define the variable self as the first line of the each loop:

    Code:
        var self = $(this);
    You've now essentially written a plug-in. The code from here on is simply specific to the plug-in we're writing for this example. You can use the code so far as a basis of your own jQuery plug-ins. In the final version (you'll see it in a bit) you can just remove the code inside the 'this.each' and replace it with your own.




    06: Store the Original Color

    In our plug-in, we have to know what color the item was before we started messing with it. To keep track of this, we're going to create an array with the original color as the 0 index value, combined with the colors set in the options. We're also going to set a value called 'color-index' which indicates which color of the array should be displayed at any time.

    Code:
        self.data('colors', [self.css('color')].concat(opts.colors));
        self.data('color-index', 0);
    You may be unfamiliar with the $(obj).data construct. It's a jQuery method that allows you to associate arbitrary data with an DOM element. In this case, we're associating both an array of colors, and a current color index.




    07: Add a Click Handler

    Since we want the DOM elements to color when clicked, we need to add a click handler. Here's how we do that:

    Code:
        self.bind('click', function() {
     
            var index  = self.data('color-index');
            var colors = self.data('colors'); 
     
            if(index < colors.length-1) {
                self.data('color-index', index+1);
            }
            else {
                self.data('color-index', 0);
            }
     
            self.css('color', colors[self.data('color-index')]);
     
        });
    This code will execute every time one of the DOM elements passed to our plug-in is clicked. It checks the current value of color-index, and if it's less then the last index value, increments it. If it's the last index value (arrays are 0 based, so index minus one is the last value) then it resets the index to zero. Finally it changes to color of the DOM element to the color indicated by the index.




    08: Finising Up

    Here's the complete plug-in code:

    Code:
        (function($) {
            $.fn.colorize = function(options) {
     
                // Defaults and options
                var defaults = {
                    colors      :   ['#FF0000','#00FF00','#0000FF']
                };
                var opts = $.extend({}, defaults, options);
     
                this.each(function() {
     
                    var self = $(this);
     
                    self.data('colors', [self.css('color')].concat(opts.colors));
                    self.data('color-index', 0);
     
                    self.bind('click', function() {
     
                        var index  = self.data('color-index');
                        var colors = self.data('colors'); 
     
                        if(index < colors.length-1) {
                            self.data('color-index', index+1);
                        }
                        else {
                            self.data('color-index', 0);
                        }
     
                        self.css('color', colors[self.data('color-index')]); 
                    });
                });
            }
        })(jQuery);
    To call the plug-in, after including it in your HTML document, add the following to your document.ready block:

    Code:
        $('p').colorize();

    Of course you'd replace 'p' with whatever selector you'd want. In this case I'm putting it on the paragraph tags for our example.

    You can download the completed plug-in and sample HTML page: create-a-plugin.zip

    In our next jQuery article, we're going to learn how to create a plug-in to enable dependant selects in HTML forms. When you choose an element in the first select, the choices in the second select are populated based on that choice.