Sunday, May 29, 2011

jQuery !!

jQuery is a library that makes it quicker and easier to build JavaScript webpages and web apps. I often find myself short of pleased with the built in functionality of AJAX and having to do some client side “touch ups” using jQuery. The essential part of a jQuery statement, the selector, is what makes jQuery a good choice for client side scripting, and an even better reason to avoid traditional java script. The selector allows you to query HTML elements to perform some logic, hence the name jQuery. Below are some of the common use of selectors.

#id

To select an element by the ID attribute. If the ID contains special character then you can escape them with backslashes. For example to find a text box with ID txtName you can write the following :

$(“#txtName”)

Then you can do any operation on the text box like getting the value or changing the css class.

element

To find all the elements in the page with the given element name. For example to get all the DIV elements following is the syntax

$(“div”)

This will find all the DIVs present in the page. You can do any operation after that.

.class

To find all elements with the given class name. The following code finds all the elements which have class name ‘RedButton’.

$(“.RedButton”)

*
This finds all the elements in the document. The syntax is :-

$(“*”)

selector 1, selector 2, selector N

This matches the combined result of all the specified selectors. We can specify N number of selectors to get a single result. Suppose you want to find all the DIVs, a text box with ID ‘txtName’ and a Button with class name ‘RedButton’. Then following is the syntax:

$(“div, #txtName, .RedButton”)

Suppose you want to change the border color of all these elements then write :

$(“div, #txtName, .RedButton”).css(“border”,”3px solid blue”);

It will change all the specified elements’ border color to blue.

There are some good tools available to test your jQuery selectors on your Apps while debugging in .Net, firebug being the most common (http://getfirebug.com/).

For a more comprehensive overview of jQuery and its syntax use the link provided for W3 schools (http://www.w3schools.com/jquery/default.asp).

jQuery cheat sheet (http://www.javascripttoolbox.com/jquery/cheatsheet/JQueryCheatSheet-1.3.2.pdf).

jQuery video (http://www.youtube.com/watch?v=7eQI90xYez0).

No comments: