Topic 4: Introduction to jQuery

What is jQuery?

jQuery is a high-level JavaScript library which allows the developer to perform sophisticated methods with just a few lines of code. For instance, with jQuery it is possible to easily manipulate the contents of a page, perform AJAX queries or create interesting visual effects such as fading page elements in and out. The corresponding code is often significantly simpler than the raw JavaScript and DOM code that one would have to use otherwise.

Therefore, jQuery can save a lot of time and effort for certain tasks. However, it should be said that it is still worth knowing the underlying "standard" W3C JavaScript and DOM functionality, as jQuery is only one of many libraries whereas the underlying W3C libraries can be used in any client-side web application running on modern browsers.

A first jQuery application






jQuery test

]]>

Hopefully it shouldn't be too difficult to figure out what the above example is doing. We define a function called hello(), and then when the document is "ready" (i.e. it has been loaded into memory), we run the hello() function with the line:

$(document).ready(hello);

In more depth, the $ (dollar) symbol represents the jQuery object. This is an object which can contain page elements or collections of page elements, depending on the context, and allows us to perform jQuery functions on those elements. $ is actually a shorthand for jQuery, so we could equally well do:

jQuery(document).ready(hello);
The ready method of a jQuery object specifies the code to run when that page element is "ready", i.e. when it has been loaded into memory. So, when the HTML document has been loaded into memory, we run the hello() function.

Another example






jQuery test

]]>

Note here how again we define a function - this time onLoad() - to run when the page is ready. This time, the function does not do anything directly (such as display "Hello!", as the first example did) but instead attaches a function to an existing page element - the button with the ID of btn1 - so that when the button is clicked, the hello() function is run.

Note the slightly different syntax to select an element with a given ID in jQuery contained to standard DOM. Whereas in the DOM we would do:

document.getElementById('btn1')
in jQuery we instead use:
$('#btn1')
Note how we use #btn1 rather than simply btn1. This illustrates an important point about selecting page elements with jQuery: we use CSS selector syntax, rather than DOM syntax. Recall for instance that to style an element with a particular ID in CSS, we use the same syntax as above:
#elem1 { background-color: black; color: yellow } 
It follows that we can use other forms of CSS selector syntax in jQuery. For instance:
$('a').click(hello);
will cause the hello() method to run when any hyperlink ('a' element) is clicked, and:
$('.important').click(hello);
will cause the hello() method to run when any page element with a class of 'important' is clicked. Other forms of CSS selector can be used too.

Manipulating page elements

jQuery allows us to easily manipulate page elements, such as change their style or content. In addition, we can achieve some interesting effects which would require relatively complex code in raw JavaScript. In this example, the contents of a div are altered with jQuery:







jQuery test

This is the test div
]]>
Note how we use the html() method to alter the contents of the div. We can also use html() with no parameters to obtain the existing contents of a page element, e.g:
alert($('#div1').html());
The previous example simply updates the contents of the div to some text. We can, however, easily add full HTML markup, e.g:
These are the new contents!');
}
]]>
We can also dynamically change the style of a page element. For instance:






jQuery test

This is the test div
]]>
Note how we specify the new style for the div as a series of attributes and values: Like standard JavaScript, background-color becomes backgroundColor to avoid the - being interpreted as a minus sign.

Returning collections

Sometimes the selector will return a whole collection of elements, e.g. $("div") will give a collection of all <div> elements on the page. Note that these elements will be returned as standard DOM elements, which we can use standard DOM functionality with,e.g.:

alert($("div")[1].style.backgroundColor);
alert($("div")[1].id); 
would give the background colour and the ID of the 2nd div on the page. However, the fact that they are DOM objects, not jQuery objects, means that we cannot use jQuery methods directly on them. For instance:
 $("div")[1].css({backgroundColor:"black"}); 
would not work. To allow us to treat any DOM object as a jQuery object, we have to convert it to a jQuery object with $ again, e.g.:
 $($("div")[1]).css({backgroundColor:"black"}); 
Note how we are converting the DOM object, $("div")[1], to a jQuery object, $($("div")[1]), with an extra $.

Other simple manipulations

jQuery allows some other simple manipulations. We can easily show and hide page elements with show() and hide():

$('#div1').hide();
$('#div1').show();

Furthermore, we can cause an element to either fade out or fade in, which will cause its background colour to gradually disappear into, or appear out of, the background. This works by gradually increasing or decreasing the element's opacity (the inverse of transparency; an opacity of 0.0 is completely transparent, an opacity of 1.0 is completely opaque). For example, with the element with the ID of div1:

$('#div1').fadeOut();
$('#div1').fadeIn();

Other manipulations

We can append extra content to an existing page element, e.g.:

$('#div1').append("Some extra content");

We can also do this the other way round with appendTo():

Some extra content").appendTo($("#div1"));
]]>
This will append the heading "Some extra content" to the div with the ID of div1.

Animation

One interesting thing we can do with jQuery is to animate page elements. Here is an example:


We pass two pieces of information to the animate() method:

Often, we might want something to happen after the animation is stopped. We can do this with the final parameter to the animate() method, e.g:

Chaining calls

Many jQuery methods return a modified jQuery object. For example, the animate() method will return a jQuery object with the modifed width/height or position. This means we can chain calls, e.g.:

$("#div1").animate({width:"800px",height:"600px"}, 3000).
    animate({width:"400px",height:"300px"},3000);
will cause the div to increase to width=800,height=600 and then decrease to width=400,height=300.

AJAX

Here is a simple example of how to send an AJAX request in jQuery:








AJAX Test

Results will appear here
Flight Destination:
Date:
]]>
The process of sending the request is actually very similar to what you have already seen with Prototype. In the ajaxrequest() function, we send an AJAX request by specifying the URL to send to, the HTTP method (GET here, could also be POST), the data to send (as a query string), and the callback function to run when we receive the response (onSuccess here).

The callback function, onSuccess(), works a bit differently to what you have already seen. Rather than using the raw DOM XML parsing functionality, we use jQuery's own, higher level, parsing. Examining the callback in more detail:

";
    }
    $("#div1").html(html);
}
]]>
As before, we set up a variable, html, which will contain the data extracted from the XML. The parameter to the function, data, is an XML DOM structure containing the data (assuming that the server sends back XML; the nature of this will differ if other types of data are sent back). We have to first convert this to a jQuery object containing the XML data, which allows us to use jQuery functions (specifically, find()); as always, we use the jQuery $ object to do this, with $(data).

The find() function gives us a collection of all instances of the specified tag, returned as another jQuery object. So here, find('flight') will give us a jQuery object containing a collection of all the <flight> tags in the data.

We then loop through the collection. Just like a normal array, we can index the collection with the square brackets [] and use length to find the length. However, if we want to use find() on each <flight> tag (so that we can extract the sub-tags <number> and <time>), we have to convert each flight tag (flights[i]) to a jQuery object using $, as before. This is because find() is a jQuery function which operates on a jQuery object, whereas flights[i] is simply a DOM object.

Note that find() gives the tag itself; if we want the text within the tag, we need to extract it with the text() function.

Obtaining more information about the response

The callback function actually has three parameters, but they are optional. The second parameter is the status (which, for a success callback, will always indicate success) and the third is an extended version of the normal AJAX XMLHTTP object. So if we wanted to debug our code and show the response as text, we could do:

";
    }
    $("#div1").html(html);
}
]]>

We can also handle error cases (the server sending back an HTTP response with a status code other than 200 OK, or non-well-formed XML being sent back) with the error callback. Here is how to set up an error callback:


Note how the error callback has three parameters: the XMLHTTP object, a text representation of the type of error, and the HTTP text status (e.g. "Not Found")

Another way to parse the XML(advanced topic)

Here is another way to iterate through the <flight> tags.

";
            }
    );

    $("#div1").html(html);
}
]]>

Here, we use a special function of jQuery, each(), to loop through each <flight> tag returned by find(). each() takes, as a parameter, a function which will be applied to each element in the collection, i.e. here, each <flight> tag. The function here is an anonymous function, one without a name. If we look at the anonymous function, we can see that it, in turn, finds the number and time tags from within the current tag. ($(this) here refers to the current object the each() function is operating on, i.e. in this case, the current <flight> tag. Having extracted the text, we add it to the html variable and finally we place the contents of the html variable into the <div>.

More info

See the jQuery home page. This contains an API reference and link to tutorials.