Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

An Introduction to jQuery, Part 1 : Page 3

jQuery is a small JavaScript library that makes development of HTML-based client JavaScript drastically easier.


advertisement

A More Complete Example

This next concrete example is an ASP.NET page that uses jQuery on the client side to fix up the page, highlighting some of jQuery's features. The following page contains a GridView to display a plain table loaded from data. I'm going to add jQuery and a bit of code to manipulate the page. You can follow along if you like by downloading the code accompanying this article. Listing 1 shows the abbreviated ASP.NET page (you'll also find a plain HTML file in the sample download).

This example applies minimal formatting to the GridView, so when you run the page you get a plain black and white grid as shown in Figure 1.

 
Figure 1. Plain Grid: The initial example shows a page with a plain black and white grid.

Now, you'll see how to use jQuery to select elements to both make the table look a little nicer and add some interactivity. First apply an alternating row effect to the table rows. To do that, add a script tag to the bottom page just above the </form> tag like this:

 
Figure 2. jQuery-Applied Striping Effect: These alternating stripes were applied using selectors and .addClass().

<script type="text/javascript"> $(document).ready( function() { $("#gdEntries tbody tr:even") .addClass("gridalternate"); .css("border","solid 1px lightgrey"); }); </script>

Figure 2 shows the alternating row-striping effect.

The jQuery()/$() Object

Take a look back at the script block and notice the $ symbol, which is an alias to the jQuery object; you can use the two interchangeably. So the code could have used jQuery(document) or jQuery("#gdEntries") just as easily as $(document) or $("#gdEntries"). The jQuery object takes a selector as a parameter. Typically selectors are expressed as strings, but you can also pass DOM elements or another jQuery object.

For example, $(document) passes a document DOM element and results in a single element wrapped set that contains the document object. $("#gdEntries") selects the gdEntries table on the page where # is the ID identifier—just as in CSS.

The $(document).ready() Handler

Notice the use of the $(document).ready() handler. .ready() is a jQuery event handler, and your first exposure to how to handle events with jQuery. This particular event handler fires when you can access the document and when scripts have completed loading. Including it in the code ensures that your code can access all the page's DOM elements and script code reliably. You can place a .ready() handler anywhere on the page; you can even have multiple .ready() handlers in a single page.

Although a .ready() handler is optional and not always required, for consistency and reliability's sake it's best to always wrap any script "startup code" into a .ready() handler to ensure consistent operation on all browsers.

jQuery implements the handler using an anonymous function, which means it declares the handler right inline with the .ready() function call:

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

This is a common practice with jQuery, because inline functions are an easy way to write the short handler code that is so common in JavaScript. There are other advantages to inline functions, but for now, just note that inline anonymous functions are a common way to write event handlers (you'll see more of them shortly). You can also pass a function pointer instead of an anonymous function:



$(document).ready( onLoaded ); ... more script here function onLoaded(e) { ... }

Selectors Again

Look back at the grid example code that performs the selection of the rows in the example. $("#gdEntries tbody tr:even") selects all the even rows in the grid view's table output. In plain English, the selector means: select the gdEntries element (#) and find any child tbody elements (a space=child) find any tr elements below those (again, a space=child) and then return a filtered set(:even=filter) that includes only the even elements.

The selector result is a wrapped set of all even rows in the table. The .addClass("gridalternate") function applies the .gridalternate CSS style to each matched element, which gives it its new highlighted appearance. Finally the .css function applies some custom styling to each matched element. Both .addClass() and .css apply their operations against all the matched elements at once.

Selectors Often Select More Than You Expect

If you're following along and running the sample code, you've probably noticed that while the example works to highlight even rows, there's also a funky side effect in the table: If you look at the pager—which ASP.NET renders as a table—you'll find that its alternating rows have also been marked up with the .gridalternate class. The problem is that ASP.NET's GridView rendering is, um…rather imprecise. It doesn't render proper tbody and tfoot tags to delineate table headers and footers, so the selector query is too broad, because it also matches the child elements, which include the child Pager table in the footer.

There are a number of ways to fix this to make it work properly. First, you can apply a filter to the selection by excluding certain elements:

$("#gdEntries tbody tr") .not(":first,:last") .filter(":even") .addClass("gridalternate") .css("border","solid 1px lightgrey");

So instead of filtering on all odd rows this code first filters the rows and omits the first and last rows (the header and the footer). It then grabs only the even items out of the remaining rows. Another (even easier) way is to select only direct children using the greater-than (>) operator rather than using the space, which selects all children:

$("#gdEntries>tbody>tr:even")

Another common and efficient way to filter elements that offers the developer the most control is via CSS class matching. You can add CSS classes or mere "marker" classes that have no matching CSS class to elements in markup.

Take another look at the way the GridView's rows are rendered:

<RowStyle CssClass="griddatarow" />

This adds a CSS class griddatarow to each row rendered in the HTML. Although the griddatarow CSS class doesn't actually exist, jQuery can still match on it in the selector expression. So the following code works:

$("#gdEntries tr.griddatarow:odd")

Or even simpler:

$(".griddatarow:odd")

The simpler version works—but the first is preferable even if it is more verbose. It's best to be as specific as possible to optimize jQuery selection in the document. The former finds the gdEntries table and then searches for children only in it, while the latter has to parse the entire document. The fewer elements matched by the first selector filters the fewer elements jQuery has to iterate over. Be precise if possible.

Suppose you wanted to select the second cell of the third row in the grid:

$("#gdEntries>tbody>tr:nth-child(3)" + ">td:nth-child(2)") .addClass("gridalternate");

Or maybe all the cells in the second column:

$("#gdEntries>tbody>tr>td:nth-child(2)") .addClass("gridalternate")

Easy! Think about how cool this is: If you had to do this manually via script code this would be a fairly complex task, but using a selector it requires only a single line that is fairly easy to write—and more importantly—easy to understand at a glance.



Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap