In 2008, Microsoft welcomed the jQuery framework by elevating its status to a first-class citizen in the Visual Studio world. This adoption accelerated jQuery's popularity and helped interest for .NET, ASP.NET, and Visual Studio developers in learning more about this fluent JavaScript library and framework. jQuery's importance is no different today as it provides developers with an elegant means to manipulate HTML5 elements with ease. In this article, I'll give you a guided tour of jQuery's feature set, to help you experience the jQuery library's simplicity and ease of use.

Getting Started with jQuery

The first step in unleashing jQuery's power is to download the beast. You can download jQuery here. Just like any other JavaScript library, jQuery needs to be referenced before it is used. You can set up the reference in a page's head section, as in the following example:

                              <script src="" type="text/javascript"></script>                               

After referring the library, you are now ready to use it. To understand the workings of the library, we'll start with a very simple application that alerts the type of DIV element on screen. The alert will be invoked when the user clicks the button. The following snippet uses the plain-vanilla JavaScript to accomplish the task.

  1. <div id="display"></div>
  2.     <input type="button" type="button" onclick="greetings()" value="Greet" />
  3.     <script language="javascript" type="text/javascript">
  4.     function greetings() {
  5.         alert(document.getElementById("display"));
  6.     }</script>

As expected, the alert box in Figure 1 clearly shows that the object is of type HTMLDivElement, which refers to a DIV element in the DOM tree.

Figure 1: DIV element showing in the alert box

Next, we'll implement the same scenario using the jQuery library, as shown in the following code sample, and examine how it differs from the previous one.

  1. <input type="button" type="button" onclick="greetings()" value="Greet" />
  2. <div id="display"></div>
  3. <script language="javascript" type="text/javascript">
  4.     function greetings() {
  5.         alert($("#display"));
  6.     }
  7. </script>

Figure 2 shows the result: The object returned is not of the type HTMLDivElement but an object. By investigating further, you'll realize that the object is of type jQuery.

Figure 2: DIV element wrapped in the jQuery object

This is where the jQuery library really shines. Instead of returning the type of the DOM element that was requested, the jQuery library returns the jQuery object. The jQuery object contains many different functions and attributes that can be used in different scenarios. This also makes it easy to add custom plug-ins to the jQuery library.

jQuery Syntax

jQuery uses a combination of XPath and CSS selector syntax to access elements inside the DOM tree. The selector syntax allows jQuery to manipulate the HTML elements as a group or as an individual element. Take a look at the following selectors in jQuery that are most commonly used in an application.

Fetching by element ID. The hash (#) sign is used to fetch the element using the element ID. This is the equivalent of using the document.getElementById function. For example:

                              $("#myTextBoxId")  //                              

returns the control whose ID is myTextBoxId.

Fetching by class name. The period (.) operator is used to retrieve the element by using the class name. For example:

                              $(".greenColorTextBoxes") //                              

returns all the controls whose class name is greenColorTextboxes.

Fetching by element type. The element tag name indicates that the element will be fetched by its type. This is equivalent to using the document.getElementsByTagName function. For example:

                              $("p") //                              

returns all the p elements on the page.


returns the <p> element with the class display.

  1. $("p#display")

returns the first <p> element with the ID display.

jQuery uses the XPath syntax to select elements using their attributes:

  • $("[href]") selects all the elements having the href attribute.
  • $("[href='#']) selects all the elements having the href attribute #.
  • $("[src='.jpg']") selects all the image elements with the source attribute ending in .jpg.

Now that you're familiar with different retrieval strategies using the jQuery library, we'll move on to discussing how to use jQuery effects.

Effects in jQuery

The jQuery framework comes with several built-in effects. If you need to create more advanced effects, you can do so using the jQuery UI library, which you can download at The effects that alter the appearance of elements are mostly UI based. The code in Figure 3 uses the built-in effect to show and hide a div element.

  1. <style type="text/css">
  3. .divStyle
  4. {
  5.         width:100px;
  6.         height:100px;
  7.         background-color:Blue;
  8. }
  11. </style>
  14.   <div id="display" style="display:none;"></div>
  16.     <input type="button" id="btnShow" value="Show" />
  19. <script language="javascript" type="text/javascript">
  21.     $(document).ready(function() {
  23.         $("#btnShow").click(function() {
  25.             $("#display").addClass("divStyle");
  26.             $("#display").show();
  28.         });
  31.     });
  33. </script>

Creating animation effects. There are times when jQuery built-in effects are not enough. In such cases, you can use the power of jQuery's animation class, which lets you create custom animations. The animation can be performed on properties consisting of numerical values—for example, width, height, and margin. You can even perform animation on color properties by assigning the color in the color code format. The following example shows how to perform animation on a simple DIV control and change its width property.

  1.   $(document).ready(function() {
  2.         $("#btnAnimate").click(function() {
  3.             $(".block").animate(
  4.             {
  5.                 width:"100%"
  6.             }
  7.             );
  8.     });
  9. });

You can even move the DIV across the screen using the marginLeft and marginRight properties, as the following example shows:

  1.   $(document).ready(function() {
  2.         $("#btnAnimate").click(function() {
  3.             $(".block").animate(
  4.             {
  5.                 marginLeft:"40%"
  6.             }
  7.             );
  8.     });
  9. });

jQuery can also manipulate color properties of the element if they're used in the form of color codes instead of names, as you can see in the following example. Note that the color animation works only when the jQuery UI reference is added (as mentioned previously).

  1. $(document).ready(function() {
  2.         $("#btnAnimate").click(function() {
  3.             $(".block").animate(
  4.             {
  5.                 marginLeft:"40%",
  6.                 backgroundColor:'#ffbfff'
  7.             }
  8.             );
  9.     });
  10. });

The previous code also demonstrates the use of multiple properties in the animation function. The animation function provides most of the features to create custom animation, but sometimes we need to plug in our custom animation function in the jQuery framework. In the next section, I'll show you how to extend the existing jQuery functions and how to successfully add your own behavior.

Creating Custom Effects by Extending jQuery

jQuery is an open extension framework that enables developers to easily extend the functionality in the existing the API. For instance, if you're interested in creating a FadeInFadeOut effect, you can easily extend the jQuery.fn class to include new methods and add custom behavior. Take a look at the following code, which demonstrates how to extend jQuery.fn to include FadeInFadeOut effects.

  1. jQuery.fn.fadeInFadeOut = function(speed) {
  2.         return $(this).fadeIn(speed,
  3.         function() {
  4.             return $(this).fadeOut(speed);
  5.          });
  6.     }

Finally, we can use our new function by employing the following code:

                              $("#divMessage").html("Item has been saved").fadeInFadeOut(3000);                              

This shows how easy it is to leverage the existing jQuery functionality and create new effects.

Drag-and-Drop Operations Using jQuery

If you've ever written plain old vanilla JavaScript to create drag-and-drop effects, you're aware of the pain you need to go through to make it work. jQuery makes it easy to perform drag-and-drop operations. The drag-and-drop operations are contained in the jQuery.UI framework.

The first task in implementing jQuery drag and drop is to create a draggable item. We will be dragging a simple DIV element. The definition of the DIV element is as follows:

  1. <div class="draggedElement"> </div>

The DIV uses the style "draggableElement" defined by the following code:

  1.   .draggedElement
  2.     {
  4.    border: 2px solid #0090DF;
  5.    background-color: #68BFEF;
  6.    width: 100px;
  7.    height: 100px;
  8.    margin: 10px;
  9.    overflow:auto;
  10.    padding:1em 1em 1em 1em;
  11.    z-index:9999;
  12.    cursor:move;
  14.     }

Next, to make the DIV draggable we need to use the jQuery draggable function. Here's the implementation:

  1. <script language="javascript" type="text/javascript">
  2.     $(document).ready(function() {
  3.         $(".draggedElement").draggable();
  4.      });
  6. </script>

And that's it! Now run the application in your browser, and you'll be amazed that by adding a single line of code you can drag the element.

Although we are able to drag the DIV element, we're dragging the original element. In most cases you do not want to drag the original element but the clone. Not to worry, since jQuery provides attributes to add this feature. To make a clone of the dragged element, just use the helper attribute, as in the following example:

  1. <script language="javascript" type="text/javascript">
  2.     $(document).ready(function() {
  3.         $(".draggedElement").draggable({'helper':'clone','opacity':'0.5'});
  4.     });
  6. </script>

This code creates a clone of the dragged element, which is easily visible because of the opacity. Figure 4 shows the clone of the dragged element.

Figure 4: Creating a clone dragged element

At this point we have implemented only the functionality for the dragged element. But this is only half of the story. The dragged element eventually needs to be dropped. This is where drop zones come into action. A drop zone is an area where a draggable element can be dropped. Creating a drop zone is straightforward, as it can be represented by a simple DIV element:


The .dropZone class is used to decorate the drop zone with styling features:

  1.   .dropZone
  2.    {
  3.             background-color: #e9b96e;
  4.  border: 3px double #c17d11;
  5.    width: 300px;
  6.    height: 300px;
  7.    margin: 10px;
  8.    overflow:auto;
  9.    position:absolute;
  10.   top: 5px;
  11.   right: 30%;
  12.   padding: 1em 0 0 0;
  14.    }

Just as we initialized the draggable element, we need to initialize the drop zone. This is accomplished by using a single line of code:


Although the drop zone has been initialized, we still need to provide it with additional information so that it knows what kinds of elements are accepted in the drop zone. The following code accomplishes this:

  1.         $(".dropZone").droppable(
  3.         {
  4.             accept: '.draggedElement',
  5.             hoverClass: 'dropZoneHover',
  6.             drop: function(ev, ui) {
  7.             }
  8.         }
  9.         );

The accept attribute represents the class that is accepted by the drop zone. This means any element having class draggedElement can be dropped into the drop zone. The hoverClass attribute represents the class that will become active once the draggable element hovers over the drop zone. Take a look at Figure 5, which shows the drop zone becoming active once the draggable element hovers over it.

Figure 5: hoverClass property in action

Now, let's take a look at the most important feature of the drop zone, the drop function:

  1. $(".dropZone").droppable(
  3.         {
  4.             accept: '.draggedElement',
  5.             hoverClass: 'dropZoneHover',
  6.             drop: function(ev, ui) {
  7.                 var droppedItem = ui.draggable.clone().addClass("droppedItemStyle");
  8.                 $(this).append(droppedItem);
  9.              }
  10.         }
  11.         );

Inside the droppable function, we have used JavaScript closures to handle the drop event. The $(this) refers to the DIV element that acts as a "DropZone" and is consuming the ".dropZone" class. The dropped item is decorated with droppedItemStyle. Once the dropped element is dropped, it is added to the drop zone element as a child. Figure 6 shows the dropped element added in the drop zone.

Figure 6: Elements added to the drop zone

The jQuery drag-and-drop API is very useful for creating interactive applications. The ease of use of the drag-and-drop framework lets a developer build complicated client-side applications more quickly.


jQuery not only provides a strong DOM manipulation library, it also includes a very handy AJAX API. jQuery provides a couple different methods to make an AJAX call, as I'll demonstrate.

The $.ajax function is the most flexible of all jQuery AJAX functions, since it allows a developer to indicate the options manually. Here is a small piece of code that invokes the Greetings web service method and returns a message to the user.

  1. $(document).ready(function() {
  2.         $("#btnGreet").click(function() {
  3.             $.ajax(
  4.             {
  5.                 type: "POST",
  6.                 contentType: "application/json",
  7.                 data: "{}",
  8.                 dataType: "json",
  9.                 url:"AjaxService.asmx/Greeting",
  10.                 success: function(response) {
  12.                     alert(response.d);
  13.                  }
  14.             }
  15.     );

The $.ajax function defined in this code calls the Greeting method contained in the AjaxService.asmx web service. Here's the implementation of the web service:

  1.   [System.Web.Script.Services.ScriptService]
  2.     public class AjaxService : System.Web.Services.WebService
  3.     {
  4.         [WebMethod]
  5.         public string Greeting()
  6.         {
  7.             return "Hello World";
  8.         }
  9.     }

Greeting is a simple method decorated with the [WebMethod] attribute. Another important thing to note about the AjaxService is that it's decorated with the [System.Web.Script.Services.ScriptService] attribute, which allows the web service to be called from the client-side code. Figure 7 shows the result.

Figure 7: jQuery Ajax API calling a web service method

You can also return XML just by changing the contentType to support XML, as shown by the following:

  1. $(document).ready(function() {
  2.         $("#btnGreet").click(function() {
  3.             $.ajax(
  4.             {
  5.                 type: "POST",
  6.                 contentType: "application/xml",
  7.                 data: "",
  8.                 dataType: "xml",
  9.                 url:"AjaxService.asmx/Greeting",
  10.                 success: function(response) {
  11.                     alert(response.childNodes[0].firstChild.textContent);
  12.                  }
  13.             }
  14.     );

It's a good idea to return the result as JSON format. JSON makes it easy to parse the object and usually represents the structure similar to the domain model.

Sending Parameters Using jQuery's AJAX API

In the previous examples, we invoked the methods and returning the results on the client side without sending any input parameters. In real-world applications, our result will depend on the parameters passed to the web method.

In the following example, our result will be based on the parameters sent by the client. We'll use the SQL Server Northwind database, since it's available on most machines. A user will be allowed to select a category from the DropDownList. When the category is selected, the related products are fetched using an AJAX request.

The following code shows the implementation of the GetProductsByCategoryId. The example uses LINQ to SQL as the data access layer, but you may use whatever data access mechanism you want.

  1.  [WebMethod]
  2.         public string GetProductsByCategoryId(int categoryId)
  3.         {
  4.             var json = new JavaScriptSerializer();
  6.             using(var db = new NorthwindDataContext())
  7.             {
  8.                 var products = from p in db.Products
  9.                                where p.CategoryID == categoryId
  10.                                select p;
  12.                 foreach(var p in products)
  13.                 {
  14.                     p.Category = null;  // removing the circular reference!
  15.                 }
  17.                 return json.Serialize(products);
  18.             }
  19.         }

The JavaScriptSerializer object has a limitation in that it cannot detect and ignore the circular references. For this reason, I've manually eliminated the circular references by setting the Category object to null. You can also return an anonymous type with the required properties to the client.

Figure 8 shows the implementation of the getProducts function, which is used to fire the AJAX request and create the product list display. In the code in Figure 8, note that the name of the parameters matches exactly with the parameter names of the web method.

  1. function getProducts() {
  3.         var list = document.getElementById('<%= ddlCategories.ClientID %>');
  4.         var categoryId = list.options[list.selectedIndex].value;
  6.         $("#productList").children().remove();
  8.         var params = "{'categoryId':'" + categoryId + "'}";
  10.         $.ajax(
  12.         {
  13.             type: "POST",
  14.             dataType: "json",
  15.             data: params,
  16.             contentType: "application/json",
  17.             url: "AjaxService.asmx/GetProductsByCategoryId",
  18.             success: function(response) {
  20.                 var products = $.evalJSON(response.d);
  22.                 for (i = 0; i < products.length; i++) {
  24.                     var product = document.createElement("li");
  25.                     product.innerHTML = products[i].ProductName;
  27.                     $("#productList").append(product);
  29.                  }
  32.             }
  33.         }
  35.         );
  37.     }

This means that if the web method parameter is called categoryId, then the AJAX call should specify categoryId as the parameter. Additionally, we've used a jQuery plug-in to evaluate the JSON string as an Object. Figure 9 shows the output.

Figure 9: Records displayed using an asynchronous call to the web method using jQuery

jQuery Support in Visual Studio 2010

The jQuery library is already supported in Visual Studio 2008, but to get the IntelliSense feature working, you need to download a Meta file and place it in a special location. In Visual Studio 2010 jQuery is treated as a first-class citizen, and the IntelliSense support is activated by default. This creates an easy way for developers to discover the jQuery API without having to refer to the documentation.

Wrapping Up

jQuery is a fascinating JavaScript library that has grown exponentially since its inception in 2006. In 2008 Microsoft embraced the popularity of this powerful library by giving it space in Visual Studio. jQuery's ease of use and advanced UI-manipulation features put it at the top of the stack of your choices of a client-side framework for any web application. Next, Dan Wahlin will provide you with some helpful web development writing tips in "5 Web Development Tips to Improve Your jQuery Coding."