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

WEBINAR:On-Demand

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.

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:

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 :

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

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:

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:

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:

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).

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:

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.

Advertiser Disclosure:
Some of the products that appear on this site are from companies from which QuinStreet receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. QuinStreet does not include all companies or all types of products available in the marketplace.

Thanks for your registration, follow us on our social networks to keep up-to-date