Creating and Using a jQuery Plug-in in ASP.NET Web Forms

Introduction

Developers often resort to code reuse techniques in their projects. As far as ASP.NET framework server side programming is concerned classes, class libraries, components, custom server controls and user controls are popular code reuse techniques. Modern ASP.NET web applications no longer restrict themselves only to server side programming. They also make use of client side scripting to render rich web forms. No wonder that Microsoft Visual Studio 2010 includes jQuery library by default as a part of newly created web site. If you are using jQuery for client side scripting then one way to reuse your client side code is to create a jQuery plug-in. Creating a plug-in allows you to bundle your reusable jQuery code in a neat way and then reuse it across web forms. In this article you will learn how to create a simple jQuery plug-in from scratch. You will also learn about certain guidelines that help you build professional jQuery plug-ins.

Sample jQuery Plugin

As an example of creating a jQuery plug-in, you will create a Count Down plug-in. The Count Down plug-in essentially displays a count down ticker that starts at a number you specify (say 10) and keeps decrementing it by one after certain configurable time gap (say 1 sec.) till it reaches zero. Such a count down ticker can be used on your ASP.NET web forms in the following situations:

  • You want to present a download link to a user but want the user to pay attention to some advertisement or notice for some time. So you can display a count down ticker for a certain period and display the actual download link only when it reaches zero.
  • You have some terms & conditions listed on your website. A common tendency is to ignore them and proceed with the download or registration. You can introduce some delay using the count down ticker so that users are prompted to carefully read the terms & conditions before proceeding further.
  • You have moved some content of your website from one location to another. When a user tries to access older location you wish to display a message informing him about the changed location and then after certain period automatically redirect him to the new location.

Creating a Plug-in

To create a jQuery plug-in, begin by creating a new website in Microsoft Visual Studio 2010. You will find that the default web site template already includes jQuery library in the Scripts folder. The following figure shows the jQuery library files included by default.

jQuery library files included by default
Figure 1

Add a new JavaScript file (.js) named CountDown.js to the Scripts folder. This file will contain your jQuery plug-in code. Open the CountDown.js file and add the following skeleton code to it.

(function( $ ){
  $.fn.CountDown = function() {
  
  };
})( jQuery );

Here, you are creating a new function property to jQuery.fn object. The name of the plug-in is defined by the name of the property (CountDown in this case). It is recommended that you pass jQuery to a self executing function so that the $ sign used by jQuery library is not overwritten by another JavaScript library.

Passing Parameters

The newly created plug-in can take parameters just like any other JavaScript function. However, considering future changes and extensibility the recommended way of passing parameters to a plug-in is as follows:

$.fn.CountDown = function(params) {
...
}

The function parameter - params - is an object that encapsulates all the configurable aspects of the plug-in. For example, our CountDown plug-in requires the following aspects to be configurable:

  • Count down start value: You should be able to specify the initial value from where the count down operation will begin e.g. 10, 100 etc.
  • Interval: Interval is the time in milliseconds after which the counter is decremented. Setting the interval essentially governs the speed of the count down operation.
  • On complete notification: You may want to get a notification once the count down reaches 0 so that you can take further action in your code. The count down plug-in should callback a function when this happens.

Passing the above settings wrapped in an object allows you to add more settings in the future with minimum changes to the calling code. A sample object that encapsulates the above settings is shown below:

{
  'counter': '10',
  'interval': '1000',
  'onComplete': MyCallback,
}

It is quite possible that developers using your plug-in may omit some of the above configuration settings. It would be better if you provide some default values for such omitted settings. The following code shows how this can be done:

$.fn.CountDown = function(params) {
 var defaults = {
   'counter': '10',
   'interval': '1000',
   'onComplete': null
 };
 if (params) {
  $.extend(defaults, params);
}

The modified CountDown function defines certain default settings as indicated by defaults variable. We need to merge the default settings and the ones supplied as the parameter to arrive at the final settings to be applied further. This is done with the help of $.extend() method of jQuery. So, if params object is passed as :

{
  'interval': '2000',
  'onComplete': MyCallback,
}

the final settings after calling $.extend() method will be:

{
  'counter': '10',
  'interval': '2000',
  'onComplete': MyCallback
}



Creating and Using a jQuery Plug-in in ASP.NET Web Forms

Maintaining Chainability

Now that you are ready to code the actual count down operation, it is important to note that your plug-in should return "this" keyword as the return value of the function.

$.fn.CountDown = function(params) {
 var defaults = {
   'counter': '10',
   'interval': '1000',
   'onComplete': null
 };
 if (params) {
  $.extend(defaults, params);
 ...
 return this.each(function(index) {...});
}

Why is this necessary? To maintain chainability of jQuery code. Consider the following jQuery code fragment:

$("some_selector").css("left",20)
                  .css("top",10);

Here you are able to call css() methods twice one after the other because the previous call returns the same set of elements as the original selector. This is a very popular and frequently used feature of jQuery and your plug-in should support this chainability by returning the "this" object whenever possible.

Count Down Operation

Now, let's implement the count down logic. Modify the each() method as shown below:

return this.each(function(index) {
 defaults.handle = window.setInterval(StartCountDown, defaults.interval);
});

The above code makes use of the setInterval() method of JavaScript window object. The setInterval() method executes the supplied code again and again after certain duration. The first parameter of the setInterval() method is the code you wish to execute and the second parameter is the time gap between multiple executions. The StartCountDown function used above is a JavaScript function and is shown below:

var element = $(this);

var StartCountDown = function() {
    if (defaults.counter >= 0) {
        $(element).text((defaults.counter)--);
    }
    else {
        window.clearInterval(defaults.handle);
        if (defaults.onComplete) {
            defaults.onComplete();
        }
    }
}

The StartCountDownvariable points to an anonymous function. The function basically displays the counter value in an HTML element using the text() method of jQuery. The keyword "this" points to the element the plug-in was invoked on. With each call to the StartCountDown function, the counter variable is decremented by 1. Once the counter value reaches 0, the clearInterval() method of JavaScript window object is called. If you have specified a callback function it will be invoked so that you can take some further action.

Using CountDown Plug-in

Once you complete the CountDown plug-in you can use it on any of the web forms. In order to do so drag and drop jQuery library file and CountDown.js file from the Microsoft Visual Studio Solution Explorer into the <head> section of the default web form. This will add two <script> blocks in the head section as shown below:

<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="Scripts/CountDown.js" type="text/javascript"></script>

Make sure that the <script> block of the jQuery library file is placed before the <script> block of jQuery plug-in file. Then add a <DIV> tag anywhere in the <body> section and set its ID attribute to countdown. Also add a textarea, a button and a SPAN tag as shown below:

<div id="countdown">
</div>
<br /><br />
<textarea id="TextArea1" cols="50" name="S1" rows="5">Terms & conditions go here...</textarea></p>
<input id="Button1" type="button" value="Submit" />
<br />
<span ID="Label1" runat="server"></span>

Add another <script> block in the head section and handle the ready() event of jQuery as shown below:

$(document).ready(function() {
    $("#Button1").attr("disabled", true);
    $("#Label1").text("You need to wait for some time to click on the Submit button.");
    $("#countdown").CountDown({ 'counter': '10', 
                                'interval': '1000', 
                                'onComplete': Notify })
                   .css("font-size", "40px")
                   .css("color", "Navy")
                   .css("padding", "10px");
});

The ready() event is raised when HTML DOM of the web form is completely loaded. The code inside the ready event handler disables the button and displays a message in the SPAN tag. Notice how the CountDown plug-in has been invoked on countdown DIV element. Also notice how we pass plug-in parameters. Since we maintained chainability inside our plug-in calls to css() method set CSS properties of the countdown DIV element as expected. The Notify() function enables the button when the count down operation is complete (see below).

function Notify() {
  $("#Button1").attr("disabled", false);
  $("#Label1").text("You can now click on the Submit button.");
}

The following figure show a sample run of the CountDown plug-in.

[Figure02.jpg]
Figure 2

Notice how the Submit button is disabled while the count down is running. When the counter reaches 0, the notify function enables the Submit button as shown below:

[Figure03.jpg]
Figure 3

Adding Methods to Plug-in

At times you want to have additional methods to your plug-in. For example, you may need stop() method that stops the count down operation. In such cases it is recommended that you don't clutter the fn namespace with too many custom methods. Instead you should store several methods in an object and then call an appropriate method by putting a check as shown below:

$.fn.CountDown = function(method) {
    if (methods[method]) {
        return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
    } else if (typeof method === 'object' || !method) {
        return methods.init.apply(this, arguments);
    } else {
        $.error('Method ' + method + ' does not exist on jQuery.CountDown');
    }

};
})(jQuery);

The CountDown function now accepts a method name as a parameter. If that method is taking some parameters they can be passed as discussed earlier.

The template of the methods object that stores various methods is shown below:

    
var methods = {
        init: function(params) {
        ...
        },
        stop: function() {
        ...
        }
    };

Though we won't discuss the stop() method here, the complete source code of the modified version is available in the code download accompanying this article.

Summary

ASP.NET web applications built around latest standards and technologies harness the power of server side as well as client side processing. Microsoft Visual Studio 2010 includes jQuery library by default for a newly created website. You can encapsulate your reusable jQuery code in a plug-in and then use it across all the web forms. Following some standards while writing your jQuery plug-in makes it more flexible and professional. The CountDown plug-in that we developed in this article shows how jQuery plug-ins can be built adhering to recommended set of guidelines.





About the Author

Bipin Joshi

Bipin Joshi is a blogger and writes about apparently unrelated topics - Yoga & technology! A former Software Consultant by profession, Bipin has been programming since 1995 and has been working with the .NET framework ever since its inception. He has authored or co-authored half a dozen books and numerous articles on .NET technologies. He has also penned a few books on Yoga. He was a well known technology author, trainer and an active member of Microsoft developer community before he decided to take a backseat from the mainstream IT circle and dedicate himself completely to spiritual path. Having embraced Yoga way of life he now codes for fun and writes on his blogs. He can also be reached there.

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: December 11, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Market pressures to move more quickly and develop innovative applications are forcing organizations to rethink how they develop and release applications. The combination of public clouds and physical back-end infrastructures are a means to get applications out faster. However, these hybrid solutions complicate DevOps adoption, with application delivery pipelines that span across complex hybrid cloud and non-cloud environments. Check out this …

  • On-demand Event Event Date: October 29, 2014 It's well understood how critical version control is for code. However, its importance to DevOps isn't always recognized. The 2014 DevOps Survey of Practice shows that one of the key predictors of DevOps success is putting all production environment artifacts into version control. In this webcast, Gene Kim discusses these survey findings and shares woeful tales of artifact management gone wrong! Gene also shares examples of how high-performing DevOps …

Most Popular Programming Stories

More for Developers

RSS Feeds