Introduction to jQuery

Introduction to jQuery 

By Carey Morris, OCI Senior Software Engineer

June 2011*

*updated on 5/8/13


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 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 [functionality removed since original publication].

  1. <html>
  2. <head>
  3. <title>jQuery Hello World</title>
  4. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
  5. </head>
  6. <body>
  7. <script type="text/javascript">
  8. $(document).ready(function(){
  9. $("#messageId1").text("Hello World from jQuery");
  10. });
  11. </script>
  12. This is Hello World from HTML
  13.  
  14. <div id="messageId1">
  15. </div>
  16.  
  17. </body>
  18. </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 JavaScript would achieve similar results:

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

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 [functionality removed since original publication].

  1. <html>
  2. <head>
  3. <title>jQuery Basic Selectors</title>
  4. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
  5. </head>
  6.  
  7. <body>
  8. <script type="text/javascript">
  9. $(document).ready(function(){
  10. $("h1").<span class="red">text</span>("Selecting a basic element");
  11. $("#exampleId").<span class="red">html</span>("<em>Selecting an id</em>");
  12. $(".important").<span class="red">css</span>('font-size', '24pt');
  13. $(".important").<span class="red">css</span>('color', 'red');
  14. });
  15. </script>
  16.  
  17. <h1>Selection examples</h1>
  18. <h2>Original h2</h2>
  19. <div id=#exampleId" class="important">Original id.</div>
  20.  
  21. </body>
  22. </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 [functionality removed since original publication].

  1. <html>
  2. <head>
  3. <title>jQuery Attribute and Custom Selectors</title>
  4. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
  5. </head>
  6.  
  7. <body>
  8. <script type="text/javascript">
  9. $(document).ready(function(){
  10. $('#colors tr:eq(2)').css('font-style', 'italic');
  11. $('#colors tr:odd').css('background-color', 'yellow');
  12. $('#colors tr:even').css('background-color', 'orange');
  13. });
  14. </script>
  15.  
  16. <h1>jQuery Attribute and Custom Selectors</h1>
  17. <table id="colors" border="1px">
  18. <tr><td>1</td><td>Red</td></tr>
  19. <tr><td>2</td><td>Orange</td></tr>
  20. <tr><td>3</td><td>Yellow</td></tr>
  21. <tr><td>4</td><td>Green</td></tr>
  22. </table>
  23. </body>
  24. </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 [functionality removed since original publication].

  1. <html>
  2. <head>
  3. <title>DOM Iteration</title>
  4. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
  5. </head>
  6.  
  7. <body>
  8. <script type="text/javascript">
  9. var log = function (msg) {
  10. $('#logArea').append('<br>' + msg + '</br>');
  11. };
  12.  
  13. $(document).ready(function () {
  14. $('#numberTable tr').each(function (index, trNode) {
  15. log('row ' + (index + 1));
  16. $(trNode).children('td,th').each(function (index, tdNode) {
  17. var value = $(tdNode).text();
  18. log('* column ' + (index + 1) + ' = ' + value);
  19. });
  20. });
  21. });
  22. </script>
  23.  
  24. <h1>DOM Iteration</h1>
  25. <table id="numberTable" border="1px">
  26. <tr><th>Number</th><th>Color</th></tr>
  27. <tr><td>1</td><td>Orange</td></tr>
  28. <tr><td>2</td><td>Yellow</td></tr>
  29. <tr><td>3</td><td>Green</td></tr>
  30. </table>
  31. <div id="logArea"></div>
  32.  
  33. </body>
  34. </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 usejq.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 [functionality removed since original publication].

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.