2503ICT: jQuery programming

Under construction!

This lecture presents a brief example-based summary of jQuery programming.


jQuery is a widely used JavaScript library. The main purposes of the jQuery library are the following:

  1. Separating JavaScript code (behaviour) from HTML documents (content).
  2. Simplifying the task of writing JavaScript in general and Ajax applications in particular.

In more detail, jQuery makes it easy to find elements of a document, to manipulate those elements by adding content, editing HTML attributes and CSS properties, defining event handlers, and performing animations. It simplifies the task of writing Ajax applications using asynchronous HTTP requests and provides general utility functions for working with objects and arrays.



We start by following the tutorial How jQuery Works.

Refer to minified jquery code in your applications either locally (minimises network traffic) or from central server (increases likelihood that code is already in user's cache). Possible central servers are http://code.jquery.com/jquery-1.9.1.min.js and http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js. Locally, the server is http://dwarf.ict.griffith.edu.au/~rwt/lib/jquery.js (an older version).

jQuery defines a single global function named jQuery() aka $(). The possible arguments of jQuery() are:

  1. CSS selector, e.g., var divs = $("div.alert");
  2. Window or document or element object
  3. String of HTML text, e.g., var img = $("", {src: url, css:{borderWidth:5}, click: handleClick}});
  4. Function, which is invoked when the document has been loaded.
The function jQuery() returns jQuery objects, to which methods may be applied.

Now, suppose you have a document like this:

<!doctype html>
<html lang="en">
    <meta charset="utf-8">
    <a href="http://jquery.com/">jQuery</a>
    <script src="jquery.js"></script>
    <script>jQuery code</script>

Let's see what happens when we add code to the second <script> element:

$(document).ready(function() {
  // Code to execute when document is loaded
  $("a").click(function(event) { alert("Welcome!"); });

This adds an event handler to each <a> element in the document, so when we click on the link, an alert box is displayed, before we go to the main jQuery page. It's similar to writing this:

<a href="" onclick="alert('Welcome!')">Link</a>

except that we don't need to add an onclick attribute to every link.

In fact, the above jQuery code can be written even more compactly:

$(function() {
  $("a").click(function(event) { alert("Welcome!"); });

For every JavaScript event such as onclick, onchange, etc., there is an equivalent jQuery function click(), change(), etc.

Another common task is adding (or removing) class attributes to (or from) elements to influence how they are styled. Suppose the document head contains:

  .bold { font-weight: bold; }
  .red  { color: red; }  

Then we can make every link appear in bold by adding the following to the second <script> element:


This example can be generalised by using an arbitrary CSS selector as the argument of $():

$(".list li").addClass("red");

This adds the class "red" to every list item in the list with class="list".

There's a similar removeClass() function.

Simple animations can be implemented using methods show() and hide() with arguments "slow" and "fast". There are many other animation methods.

Note how these examples allow us to avoid writing style attributes and event handlers in our documents, thus separating presentation and behaviour from content.

See this simple example (zipped archive), which illustrates these methods.

The tutorial Getting Started with jQuery expands on these techniques and introduces many new ones.

For example, jQuery has methods attr() for getting and setting attribute values of elements, css() for adding styles to elements, hasClass() for testing for classes of elements, addClass() and removeClass() for adding and removing classes of elements, val() for getting and setting the value attribute (or selection state) of form elements. Methods text() and html() are used to get or set the plain text or HTML content of one or more elements.


$("form").attr("action");            // get the action of the first form
$("#icon").attr("src", "icon.gif");  // set the src attribute
$("#banner").attr({src:"banner.gif", // set 4 attributes at once
                   width:720, height:64});
$("div.note").css("border", "solid black 2px"); // set the CSS border style
$("#surname").val();                            // get the value of a text field
$("#email").val("Invalid email address");       // Set value of a text field
$("head title").text();              // get document title 
$("head title").text("New heading"); // set document title

jQuery is designed in part to simplify the task of writing Ajax applications. The Ajax functions and methods allow applications to laod data asynchronously from the server withoout a browser page refresh.

The Ajax functions and methods are described in the jQuery documentation. Perhaps the three most important functions are ajax(), get() and post(), which perform an asynchrounous HTTP request, load data from the server using an HTTP GET request, and load data from the server using a HTTP POST request, respectively. Functions get() and post() are basically simpler ways of calling function ajax().

Function get() takes a URL, a map or string that is sent to the server with the request, a callback function that is executed if the request succeeds, and the type of data expected from the server (xml, json, script or html). The callback function is passed the return data (xml element, text string, JavaScript file or JSON object) depending on the MIME type of the response. It is also passed the text status of the response.

The following example omits the input and result type arguments.

$.get('test.html', function(data) {
  alert('Data was returned.');

Function post() takes the same four arguments as function get(). The callback function takes an additional "jqXHTR" object, an extended XMLHttpRequest object.

Here is a simple example:

  {name: "John", time: "2pm"},  
  function(data) {
    alert('Data loaded: ' + data);
  }, "xml");

This rate me example (zipped archive) is a very simple illustration of the use of these functions taken from the above tutorial. It invites the user to rate the current page on a scale of 1 to 5. Selecting a rating initiates an asynchronous HTTP request to the script rateme.php, which stores the rating and returns the average and number of past ratings.

In a more realistic example, the results might be appended to the page content instead of replacing the page content.

Note how the JavaScript code in index.php avoids all references to XMLHttpRequest objects and properties such as readyStatus of these objects, thus simplifying the task of writing Ajax applications.

It is possible to extend jQuery by writing plugins.

These notes just touch on the features of jQuery. To do any serious programming, you really need to refer to the documentation or Flanagan's text.

jQuery Mobile

jQuery Mobile is a JavaScript library that extends jQuery to simplify the unified development of HTML5-based Web applications for touch-enabled mobile devices.