RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


An Introduction to jQuery, Part 1 : Page 5

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


Building On the Example

Suppose you wanted to extend the earlier grid example by highlighting grid rows when a user hovers over them with the mousse—regardless of which browser the client is using. The following code uses jQuery's .hover() event function, which fires repeatedly as a user hovers over an element. The .hover event function takes both entry and exit event function handlers as parameters.

For example, change the previous selector chain to:

       .hover( function() {
       }, function() {                 
Note that the example re-arranges the sequence of the original operations a little so that it applies the hover behavior to all rows. After that, it filters the list to include only the even rows so it can apply the alternating style.

The .hover() function is an example of a jQuery event handler. It happens to be a special one, because unlike most it takes two callback functions as parameters. The first callback is for the mouseenter operation, and the second for the mouseout operation. jQuery handles .hover() intelligently, detecting only "real" mouseout events when the mouse leaves the container (unlike the DOM mouseout event which also fires when entering child elements).

Running the page now causes an orange highlight to appear for each row that the mouse hovers over.

This next example handles clicks on the row, popping up a dialog that shows the value in the third column, using the following .click() handler:

       .hover( function() {
       },function() {
       .click( function(e) {
           alert("Amount: " +  
Figure 3. Interactive Grid: Here's how the grid looks after adding hovering and click event handling.
This code hooks up a click handler to every row in the matched set. Figure 3 shows what the grid looks like now. Remember, jQuery always calls event handlers in the context of the element that caused the event—so this points at the row DOM element. You can turn this into a jQuery object $(this) and then apply further filtering to this single element to find the third child cell and display its content.

Displaying the amount in column three is not all that useful though. A more common scenario is for navigation where a click navigates to a different page or performs some AJAX request based on the selected row. Unfortunately the ASP.NET GridView doesn't provide any sort of ID or context on the client side, so it's not easy to take a context-based action. To navigate or post data in some sort of useful context, you have to take matters into your own hands. It's pretty easy to fake GridView context though, knowing that you can use jQuery to easily access document content. You simply embed an ID value into the generated content of one of the cells. The grid already has a template column so I'll change it to:

   <asp:TemplateField ItemStyle-
       <div style="display:none">
          <%# Eval("pk") %></div>
       <div id="entrytitle">
          <%# Eval("Title") %></div>
       <div id="entrydescription">
         <%# Eval("Description")) %></div>
That change embeds the PK value into the generated output. You can then handle the .click() event by retrieving that PK value in the second column, looking at the first <div> tag and getting its text:

   .click( function(e) {
   var pk = $(this)
      .find("td:nth-child(2) div:first-child")
         "someotherpage.aspx?id="+ pk;
Using jQuery and its flexible selector syntax, you can easily store data in the HTML and the DOM, putting your state content directly into the HTML, and then getting at it via selectors, as in this example. It also makes it possible to extend even an inflexible component such as the GridView, by making it more dynamic. Approaches like this can completely change the way you think about the purpose of client UI and interactivity. For example, you can do in-place editing of content in the browser and then pick up that content later to post to the server via AJAX or postback. The possibilities are endless.

Creating New HTML and Embedding It into the DOM

You're not limited to acting on existing DOM objects. You can also create jQuery objects by passing an HTML string as the parameter to the jQuery object. Creating HTML and adding it to the document is as easy as:

You can inject HTML anywhere in the document with the .appendTo() or .prependTo() functions, which insert into the child items of the selector element(s). Or you can use .append() and prepend()to insert after or before the currently selected element instead.

You can also .clone() existing nodes easily. Try this on the example above:

When you do that, you'll see the entire GridView duplicated in the page. That may not seem terribly useful, but there are a number of situations where cloning makes sense. For example, you can use cloning for a sort of templating mechanism. To insert a new row with new content in the table above you can use code like this:

   var row = 
      .text(new Date().formatDate("MMM dd));
      .html(new Date().formatDate("hh:mm:ss"));
      .text( 199.99.formatNumber("c"));
Author's Note: The format functions are helper functions and are also provided with the downloadable source. The nice thing with this approach is that you don't have to create HTML on the client-you're only injecting text or data and maybe a little markup rather than HTML strings. The HTML structure comes from the cloned DOM element and you're only "filling in the blanks."

Content doesn't have to pre-exist either. You can load "template" content from non-visible HTML elements on the page or embedded inside of a script block.

The example above is simplistic because it simply injects static content, but you could just as easily retrieve the content from an AJAX callback or form input fields and load that into the cloned "template."

Templating is a powerful topic and you'll see more in the follow-up article, which looks at a couple of different templating tools you can use in combination with jQuery. (If you're eager to check it out now, look at jTemplates or John Resig's cool Micro-Template engine.)

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date