Introduction to jQuery - updated on 5/8/13

by
Carey Morris, Senior Software Engineer
Object Computing, Inc. (OCI)

Introduction

In today's IT environment, many companies have invested heavily into building Swing-based desktop applications. This adds client-side maintenance and sometimes WebStart to launch. The move to a more modern user interface demands a browser-based thin client based on JavaScript to provide a long term solution. Many proven JavaScript libraries exist to assist in creating browser-based applications that give the user many of the same capabilities that were available natively on the desktop (Rich Internet Application or RIA). These JavaScript frameworks must provide cross-browser capabilities that perform well and are easy to use. These include jQuery, MooTools, Prototype, Script.aculo.us, YUI (Yahoo User Interface) and more.

This article introduces jQuery (http://jquery.com/) - the most popular JavaScript library in use today. jQuery currently has a 91% market share of websites that use various JavaScript libraries and 66% of the top 10,000 websites. It's nearest competitor, MooTools, has 7% and 2% respectively.

jQuery is designed to help simplify navigating HTML documents, handle events (form, browser, mouse, keyboard), animation effects, and add Ajax interactions to web pages - all in a small package (24k minimized). It is free and open sourced using the MIT and GPL licenses. jQuery is also extensible using a plugin (http://plugins.jquery.com) architecture to allow extension and customization.

This introduction to jQuery assumes a basic understanding of HTML, JavaScript and CSS on the part of the reader.

Using the library and caching

jQuery can be downloaded from HERE. For this introduction we will use version jQuery 1.6.1. For production deployments, jQuery provides a minified version (http://code.jquery.com/jquery-1.6.1.min.js) that is compressed to remove whitespace in order to reduce download time and shorten variable and function names. An uncompressed version (http://code.jquery.com/jquery-1.6.1.js) is provided so that you can see a formatted version of the source code. This can be useful for debugging.

jQuery comes as a single JavaScript file that may be include in your web page by linking to a local copy or to a public server.

The simplest way to include the jQuery library in your JavaScript is to point to a local copy with the following line included in your html header.

<script type="text/javascript" src="js/jquery.js"></script>

The jQuery library is also hosted in public places such as Google or Microsoft. The Google AJAX libraries Content Delivery Network(CDN) (http://code.google.com/apis/libraries/ ) provides the ability to link selected libraries directly to Google's network of data centers. This provides lower latency, increased parallelism and caching.

<script type="text/javascript"
        src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>

By pointing to a CDN provided URL, the data center closest to the user will deliver the static content faster and reduce load on your server. With widespread use of common libraries on popular websites, it's likely that your target library is already locally cached on your local disk - no download is required! This is even more likely due to the widespread use of jQuery.

Note that this link refers to a specific version of jQuery. To ensure that your web page dependencies are not broken (and for other reasons), you should link to a specific version and not to the latest release.

Getting started with Hello World and the jQuery syntax

Here is a simple script to output the text "Hello World from jQuery". Click HERE to run.

<html>
<head>
    <title>jQuery Hello World</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
</head>
<body>
    <script type="text/javascript">
        $(document).ready(function(){
            $("#messageId1").text("Hello World from jQuery");
        });
    </script>
This is Hello World from HTML

<div id="messageId1">
</div>

</body>
</html>

$() is a jQuery function. The ready function calls a given function when DOM elements are ready or fully loaded. In the example above an anonymous function is used which contains calls to jQuery functions to dynamically create a message and append it to the HTML tag with id "messageId1".

We can compare this jQuery hello world example to how JavaScrpt would achieve similar results:

window.onload = function() {
    document.getElementById('messageId1').innerHTML = "Hello World from JavaScript";
}

As a shorthand, the $(document).ready(fn) can be expressed as $(fn).

$(function() { alert("Hello World from jQuery"); });

jQuery can also be used with other libraries that define $ (for example, Prototype). Calling jQuery.noConflict() causes jQuery to give up use of $. When that is done, code must use "jQuery" in place of "$".

jQuery.noConflict(function() { alert("Hello World from jQuery"); });

Basic Selectors

jQuery offers a powerful set of tools for matching a set of elements in a document. Our Hello World example selected they div element by id (#id). Elements can be selected by element name, id, CSS class, children or decendents of a specific element, and multiple selectors.

Click HERE to run.

<html>
<head>
  <title>jQuery Basic Selectors</title>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
</head>
 
<body>
  <script type="text/javascript">
    $(document).ready(function(){
      $("h1").text("Selecting a basic element");
      $("#exampleId").html("<em>Selecting an id</em>");
      $(".important").css('font-size',  '24pt');
      $(".important").css('color', 'red');
    });
  </script>
  
  <h1>Selection examples</h1>
  <h2>Original h2</h2>
  <div id=#exampleId" class="important">Original id.</div>

</body>
</html>

As we can see from these examples, jQuery makes it very easy to select and manipulate elements of a webpage.

$("h1").text("Selecting an basic element");

This selects all 'h1' elements and sets their contents to the specified text.

$("#exampleId").html("<em>Selecting an id</em>");

This selects the element with id "#exampleId" and sets the contents to the specified HTML text. The string passed to the HTML function may contain embedded HTML. With the text function, an HTML contained in the passed string is removed. In this case, the text is wrapped with <em/> for emphasis.

$(".important").css('font-size',  '24pt');
$(".important").css('color', 'red');

The period (.) and class name select all elements with the class "important" and sets the css to the color red.

Selectors Based on Attributes and Custom Selectors

Elements can also be selected by jQuery based on their attribute values:

Selectors that begin with [ or : are sometimes referred to as "filter selectors" because they filter out earlier matches. The others are "find selectors".

Other selectors allow selection based on parent/child relationships:

These custom selectors are not in CSS but are added by jQuery:

Note that these selectors are 0-based

Other assorted custom selectors:

This example demonstrates some of the previous custom selectors in action. Click HERE to run.

<html>
<head>
  <title>jQuery Attribute and Custom Selectors</title>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
</head>
 
<body>
  <script type="text/javascript">
    $(document).ready(function(){
      $('#colors tr:eq(2)').css('font-style', 'italic');
      $('#colors tr:odd').css('background-color', 'yellow');
      $('#colors tr:even').css('background-color', 'orange');
    });
  </script>
  
  <h1>jQuery Attribute and Custom Selectors</h1>
  <table id="colors" border="1px">
    <tr><td>1</td><td>Red</td></tr>
    <tr><td>2</td><td>Orange</td></tr>
    <tr><td>3</td><td>Yellow</td></tr>
    <tr><td>4</td><td>Green</td></tr>
  </table>
</body>
</html>

DOM Iteration and Filtering

The result returned from a selection is a jQuery object that represents a collections of matched elements. When a method is called on a jQuery object it implicitly iterates over the collection acting on each DOM element.

jq.each(callback) iterates over each element of the collection contained in the jQuery object denoted by jq. The callback function can be named or anonymous and takes as arguments the index and DOM node.

Other methods are available for DOM Traversal. These include:

The following code finds each row in the table identified by "colors" and calls a function with each element index and DOM node. This function logs the row in the log area (id=logArea). Then for each row, the children elements that match 'td' or 'th' are logged as values. Click HERE to see this in action.

<html>
<head>
  <title>DOM Iteration</title>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
</head>
 
<body>
  <script type="text/javascript">
    var log = function (msg) {
      $('#logArea').append('<br>' + msg + '</br>');
    };

    $(document).ready(function () {
      $('#numberTable tr').each(function (index, trNode) {
        log('row ' + (index + 1));
        $(trNode).children('td,th').each(function (index, tdNode) {
          var value = $(tdNode).text();
          log('* column ' + (index + 1) + ' = ' + value);
        });
      });
    });
  </script>
  
  <h1>DOM Iteration</h1>
  <table id="numberTable" border="1px">
    <tr><th>Number</th><th>Color</th></tr>
    <tr><td>1</td><td>Orange</td></tr>
    <tr><td>2</td><td>Yellow</td></tr>
    <tr><td>3</td><td>Green</td></tr>
  </table>
  <div id="logArea"></div>
  
</body>
</html>

Note that trNode is wrapped by $(trNode) in order to turn the DOM node into a jQuery object so methods like children can be called.

Adding, Removing, Hiding and Showing Elements

jQuery makes it easy to manipulate content in a webpage. With just a few calls, you can easily add, remove, replace, show or hide page elements.

Adding elements

Removing Elements

Hiding and Showing Elements

There are also built in effects when hiding and showing.

In the previous example, we used append to add messages to the log area.

$('#logArea').append('<br>' + msg + '</br>');

Event Binding

Event bindings are used to register behaviors to take effect when the user interacts with the browser, and to further manipulate those registered behaviors.

There are three basic event handler methods in jQuery - bind, live, and delegate. bind is the basic workhorse of event handlers.

To bind an event handler function to selected elements use jq.bind(event-type, handler);. Handler functions are passed an event object that describes the event. In the handler function, this refers to element on which event occurred.

To unbind an event handler function from selected elements use jq.unbind(event-type, handler);. To unbind a given handler from all events, omit event-type. Omit handler to unbind all handlers from a given event. Omit both to unbind all handlers from all events.

To bind an event handler function to selected elements for only one execution use jq.one(event-type, handler);. This automatically unbinds after first matching event occurs.

To bind an event handler function to existing AND future elements that match a selector $(selector).live(event-type, handler);. To unbind an event handler function from existing AND future elements that match a selector $(selector).die(event-type, handler);. One example where these are useful is adding handlers to elements that appear in table rows when new rows may be dynamically added later.

Shorthand Event Binding

As an alternative to named binding, each of these shorthand methods can be invoked with no argument to trigger the indicated event on selected elements as if the user caused it.

This example demonstrates the use of the change, click, and live event handlers. Click HERE to run.

Summary

This introduction to jQuery has covered the basics of jQuery selection and event handling. jQuery is by far the most popular library today for making JavaScript simpler to use and understand. With a basic understanding of jQuery, users may want to explore jQuery Ajax, JSON, jQuery Plugins and jQuery UI to achieve a RIA that really shows what an browser application are capable of.

References

Special thanks to Mark Volkmann for making this SETT article possible.


Valid XHTML 1.0 Strict [Valid RSS]
RSS
Top