:::: MENU ::::

Thursday, March 5, 2009

Introduction

JQuery is a powerful JavaScript library that enables the developer to do more in less code, a point which I hope to show you in this article. Rather than give a brief overview, let's learn in this article by example.

To start, JQuery uses the $ notation to target the HTML elements for retrieval or manipulation purposes. As an example, take a look at some of the ways you can access HTML elements.

Listing 1: Accessing a single or array of elements

  1. $("p") //accesses all p elements  
  2. $("#pid") //accesses an element by its ID  
  3. $(".p") //accesses elements using a class name  

The notation you see above, using an identifier within the $() notation, is a common approach across most JavaScript libraries. Not all libraries provide all three of these features as simple as JQuery does. Whether it's a single element or an array, JQuery makes working with elements easy. Let's take a look at what can be done with JQuery.

Selectors

As we saw above, JQuery makes it easy to access elements by an id, css class, or tag name. JQuery goes beyond this by providing a wide array of selectors all in one statement. The first selector I will demo provides the capability to drill down through a hierarchical structure, such as a table in Listing 2.

Listing 2: Parsing tables

  1. $("table > tbody > tr") //processes all table rows in a table  
  2. $("#t1 > tbody > tr") //processes all table roes in one specific table  
  3. $(".table > tbody > tr") // processes tables with the table class  

The greater than notation specifies the hierarchy of elements that must exist to match all TR elements; these patterns will not match TR elements within the header or footer of a table, nor would it match a table without a body element. Note that the id or class matching can be used anywhere in the selector. For instance, replacing the tr tag with a css class called "tablerow" would also work, but limits the results (which may be a more desired result).

Selectors can target one or multiple elements using a variety of patterns. Targeting multiple elements can be done by matching all elements of a specific tag type [$("p")], ore match multiple elements simultaneously using a comma separated list like: p, span, div. Selectors can also use filters that restrict the results returned, as shown in Listing 3.

Listing 3: Some of the available filters

  1. $(p:first)  //first in range  
  2. $(p:last)  //last in range  
  3. $(table > tbody > tr:even)  //even rows  
  4. $(table > tbody > tr:odd) //odd rows  
  5. $(p:eq(1)) //at index 1  
  6. $(p:gt(2)) //greater than 2, elements 3 and beyond  
  7. $(p:lt(10)) //less than 10, 0-9  
  8. $(p:empty) //where p has no children  
  9. $(p:parent) //where p is a parent  

Some of these filters are handy; for instance, when styling tables, using the :even and :odd filters work very well to create an alternating pattern. Using the :lt filter is good when you want to get the top 10 of something within a specific list. Accessing elements using an index (:eq) or getting the :first or :last in a list is always handy. Attributes can also be used to filter the results returned. For instance, take a look at using attributes to filter data.

Listing 4: Accessing text control values

  1. $("input[type='text']").css("color", "red");  

This is by no means a complete list; you can find more selectors at: http://docs.jquery.com/Selectors.

Accessing Content

JQuery provides access to the content of elements that expose a value and those that do not. Depending on the type of elements being accessed, these methods can extract this information. For instance, take a look at some of the assignments below.

Listing 5: Accessing content

  1. $("#span").html();  
  2. $(:input).val();  
  3. $("#name").text();  

In the examples above, some methods are used to extract information out of the underlying result set. The html() method allows the developer to extract the inner HTML information from the target element. The result-set must be singular in nature; this means that the results returned via $() has to be a single element; otherwise, the first element's value is returned. The val() method works differently; it can return a single result of the first element in the result. Notice the :input notation; this targets all text input controls. There are a couple of these filters available, which you can find out more at jquery.com.

When using these values, know that val() method looks for elements that have a value property associated with them. The html() method looks for the inner HTML contents of an element. The text() method gets the text of an element; this is the only multi-range method, as it concatenates the values into a single string.

Each of these methods works in a get and set mode; the get mode is the empty method call; passing in no value to the method performs a get call. When passing in a value, this performs a set operation, overriding the inner content.

There are other methods that can be used to manipulate HTML markup I didn't mention. One of the more common options is the css() method. This method takes two parameters: the name of the css value to modify, and the new value to apply. It can also take a collection of name value pairs in a class (noted by the {}). This makes it easy to apply css rules to a single or multiple elements.

Another popular method is the attr() method; this method reads or writes attributes of an element. To write an attribute, provide the name and value of the attribute to the method. Or, to set more than one attribute at a time, use the {} notation to set properties in bulk.

Take a look at some of the following examples.

Listing 6: Using css() and attr()

  1. $("p").css("background-color", "blue");  
  2. $("p").css({ "background-color" : "navy", "color", "white" });  
  3. $("button").attr("disabled", "disabled");  

These are by no means the only methods; there are other methods for modifying content; there are plenty of other methods that can modify the markup, such as wrapping content with HTML markup or replacing content with a substitute. You can find more documentation at: http://docs.jquery.com/Manipulation

Traversing Content

JQuery includes helpful methods that traverse the result set, or affect the results in a variety of ways. For instance, JQuery can navigate up or down the stack using the parent() or children() methods. These methods assume a single result of course, but these options are available.

In addition, other methods like the filter() method can trim down a larger result set; for instance, suppose that a JQuery result returns a collection of paragraph elements. The filter method can apply an expression that reduces the total number of results that will have a chained response applied to it. There are plenty of other methods for accessing the previous, next, sibling, and other related elements too.

Let's take a look at some of these methods in use:

Listing 7: Using the parent(), children(), and filter() methods

  1. alert($("#pid").parent().tagName);  
  2. $("#pid").children().hide();  
  3. $("#pid").children("[type='hidden']:first").val();  
  4. $("p").filter(".highlighting").show();  

There are plenty of other methods used for traversing content available at: http://docs.jquery.com/Traversing.

Events

JQuery can listen to object events. The most notable and frequently used event is the ready event, an event that fires when the browser has loaded. To attach to the ready event, do the following.

Listing 8: Attaching to the ready event

  1. $(document).ready(function() { .. });  

The ready event is where most of the code processing is placed, but this isn't required. If using ASP.NET AJAX, the page's client-side init or load event handler is another opportune place to put initialization code in. JQuery isn't limited to the ready event; it can also listen to other events like:

Listing 9: Handling a button click

  1. $("#buttonid").click(function() { alert("BUTTON CLICK"); }  

Handling events is a pretty standard process, as shown above. In the event definition, the this pointer actually refers to the object that raised the event (the button that was clicked, in the case of listing 7).

There are some other options to attaching events, but that is out of scope for this article. You can find more about events at: http://docs.jquery.com/Events.