Developing JQuery Plugins

If you are experienced with web technology and jQuery then you might also be familair with jQuery third-party plugins that provide a bevy of options for enhancing our application user experience but sometimes we need to reach a bit further and write code that can be reused by others by just placing it on servers or possibly you want to package it as an entirely new plugin. So, this article provides a complete introduction to jQuery Plugins Development.


Download the Project


Introduction


In this article I'll be developing a jQuery plugin to find the sum and average of data that is available in a web page in HTML format. I'm not going to use on-page embedded jQuery or JavaScript methods to find the sum and average whereas I'll create a separate jQuery plugin that can be used by anyone by just using the URL reference in the manner that a normal jQuery library or plugin does. Now look at the image:
















In the above image, you can see the marked calculation that is done by a recently developed plugin. So, let's get started and for this use the following the steps.


Step 1


In this step I'm going to create a new JavaScript file including a definition of my jQuery plugin. Why JavaScript file? Because jQuery is nothing more than a JavaScript library, so jQuery plugins always have a .js extension.


Now go ahead and create a file named "ITORIANjQueryLib.js" and add the following code:


(function($) {

    $.sum = function(array) {

        var total = 0;

        $.each(array, function (index, value) {

            value = $.trim(value);

            value = parseFloat(value) || 0;

            total += value;

        });

        return total;

    };


    $.average = function(array) {

        if ($.isArray(array)) {

            return $.sum(array) / array.length;

        }

        return '';

    };

})(jQuery);


In the above code you can see two separate functions:


$.sum = function(array) {


and


$.average = function(array) {


The sum and average methods will accept an array, calculate and returning the result; the remaining code is simple and very friendly.


Step 2


In this step I'm going to create the HTML document that will consume the above jQuery plugin by just a library file reference and a method call from page logic.


<body>

    <form id="form1" runat="server">

    <div>

        <table id="productlist">

            <thead>

                <tr>

                    <th>Product</th>

                    <th>Quantity</th>

                    <th>Price</th>

                </tr>

            </thead>

            <tbody>

                <tr>

                    <td>Creative Inspire 5.1 Speakers</td>

                    <td>4</td>

                    <td>16200</td>

                </tr>

                <tr>

                    <td>SONY VGN- P 23G Q / W</td>

                    <td>1</td>

                    <td>46990</td>

                </tr>

                <tr>

                    <td>Microsoft Mouse</td>

                    <td>1</td>

                    <td>250</td>

                </tr>

                <tr>

                    <td>Microsoft Keyboard</td>

                    <td>1</td>

                    <td>350</td>

                </tr>

            </tbody>

            <tfoot>

                <tr id="sum">

                    <td>Total</td>

                    <td></td>

                    <td></td>

                </tr>

                <tr id="average">

                    <td>Average</td>

                    <td></td>

                    <td></td>

                </tr>

            </tfoot>

        </table>

    </div>

    </form>

</body>


The output of the above HTML markup can be seen in the image at the very top of this article. There is however something you need to notice; the table has an id attribute and its value is "productlist", the table footer has two rows and each has the id attribute and the values are 'sum' and 'average'. I'll place the calculated result in the second column of sum row and thirrd column of average row.


Step 3


Now you have a jQuery Plugin and a demo page to test this. Now one more thing we need to do is to make the library call from the web page. Here is the code:


    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

    <script type="text/javascript" src="ITORIANjQueryLib.js"></script>

    <script type="text/javascript">

        $(document).ready(function () {

            //Get SUM of Quantity

            var $productlist = $('#productlist tbody');

            var quantities = $productlist.find('td:nth-child(2)').map(function (index, qty) {

                  return $(qty).text();

            }).get();


            var sum = $.sum(quantities);

            $('#sum').find('td:nth-child(2)').text(sum);


            //Get AVERAGE Price

            var $productlist = $('#productlist tbody');

            var prices = $productlist.find('td:nth-child(3)').map(function (index, qty) {

                  return $(qty).text();

              }).get();


            var average = $.average(prices);

            $('#average').find('td:nth-child(3)').text(average.toFixed(2));

        });

    </script>


In the above code, you can find three script sections. The first script will call the jQuery basic library; the second script will import our newly created jQuery Plugin to the page and the last script will make the function call which is defined in our jQuery Plugin file.


Now we are all set to distribute our newly created jQuery Plugin to the developer community by just placing this .js file on servers and populate its URL.


You can download the project from here and test it yourself.


I hope you like it. Thanks.