:::: MENU ::::

Tuesday, February 24, 2009

A brief introduction to jQuery and ways in which we can integrate it into ASP .NET

Introduction

In September 2008 Scott Guthrie, the head of the ASP.NET team, announced in a blog post that Visual Studiohttp://images.intellitxt.com/ast/adTypes/mag-glass_10x10.gif would be shipping with the jQuery library. He writes:

“jQuery is a lightweight open source JavaScript library (only 15kb in size) that in a relatively short span of time has become one of the most popular libraries on the web. A big part of the appeal of jQuery is that it allows you to elegantly (and efficiently) find and manipulate HTML elements with minimum lines of code … There is a huge ecosystem and community built up around JQuery. The jQuery library also works well on the same page with ASP.NET AJAX and the ASP.NET AJAX Control Toolkit.”

With that, JQuery is officially embraced by ASP.NET.

A brief introduction of JQuery

jQuery is the star among the growing list of JavaScript libraries. A few of its characteristics are light-weight, cross-browser compatibility and simplicity. A common task that sometimes takes 10 lines of code with traditional JavaScript can be accomplished with jQuery in just one line of code. For example, if you want to dress up a table with an ID mytable with alternative color for every other row, you can simple do this in jQuery. 

Listing 1: jQuery code for making a zebra-style table

  1. <script>  
  2. $(function() {  
  3.     $("table#mytable tr:nth-child(even)").addClass("even");  
  4. });  
  5. </script>  

The magic dollar sign ($) and a chain of operations

In jQuery, the most powerful character / symbol is the dollar sign. A $() function normally returns a set of objects followed by a chain of operations. An example

  1. $("div.test").add("p.quote").html("a little test").fadeOut();  

Think of it as a long sentence with punctuations. Indeed it is a chain of instructions to tell the browser to do the following:

  1. Get a div with class name is test;
  2. Insert a paragraph with class name is quote;
  3. Add a little text to the paragraph;
  4. Operate on the DIV using a predefined method called fadeout.

So there it is, the first two basics: $() and chainable.

More