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].
- <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 JavaScript 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 [functionality removed since original publication].
- <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").<span class="red">text</span>("Selecting a basic element");
- $("#exampleId").<span class="red">html</span>("<em>Selecting an id</em>");
- $(".important").<span class="red">css</span>('font-size', '24pt');
- $(".important").<span class="red">css</span>('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:
- Has attribute with any value -
$('___[attr]')
- Has attribute with specific value -
$('___[attr = value]')
- Has attribute without specific value -
$('___[attr != value]')
- Has attribute with value starting with -
$('___[attr ^= value]')
- Has attribute with value ending with -
$('___[attr $= value]')
- Has attribute with value containing -
$('___[attr *= value]')
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:
$('___:first-child')
$('___:last-child')
$('___:nth-child(n)')
- n is 1-based for CSS compatibility$('___:only-child')
These custom selectors are not in CSS but are added by jQuery:
$('___:eq(index)')
:lt(n), :gt(n)
$('___:odd')
$('___:even')
$('___:contains(value)')
Note that these selectors are 0-based
Other assorted custom selectors:
- Various kinds of "input" elements
$(':input')
- includes input, textarea, select and button elements- input elements with a specific type attribute
$(':type')
where type is text, checkbox, radio, password, submit, reset or file
- button elements and input elements w/ type="button"
$(':button')
- Form elements that are enabled or disabled
$(':enabled')
or$(':disabled')
- Checked checkboxes and radio buttons -
$(':checked')
- Selected option elements -
$('#selectId > :selected')
- the part before the > is a direct parent of the part after the >
- omit > for ancestor relationships
- Container elements -
$('parent:has(child)')
- finds all parent elements that have at least one child element of a given kind
This example demonstrates some of the previous custom selectors in action. Click HERE to run [functionality removed since original publication].
- <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:
- Filter a collection of elements
jq.filter('selector')
orjq.filter(boolean-fn)
- Find children
jq.children('selector')
- Find descendants
jq.find('selector')
- Find siblings
- only next sibling -
jq.next()
- all following siblings -
jq.nextAll()
- only previous sibling -
jq.prev()
- all previous siblings -
jq.prevAll()
- one of those plus context element -
jq.one-of-the-above.andSelf()
- all siblings plus context element -
jq.parent().children()
- only next sibling -
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].
- <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
jq.append(content)
- appends content to interior end of each element in jq- content may be HTML String, DOM element or jQuery object
jq.appendTo(selector)
- appends each element in jq to interior end of elements matched by selectorjq.prepend(content)
- prepends content to interior beginning of each element in jqjq.prependTo(selector)
- prepends each element in jq to interior beginning of elements matched by selectorjq.after(content)
- inserts content after each element in jqjq.insertAfter(selector)
- inserts each element in jq after each element matched by selectorjq.before(content)
- inserts content before each element in jqjq.insertBefore(selector)
- inserts each element in jq before each element matched by selectorjq.wrap(wrapping-element)
- wraps around each matched element individuallyjq.wrapAll(wrapping-element)
- wraps around all the matched elements as a groupjq.wrapInner(wrapping-element)
- wraps around content of each matched element individuallyjq.replaceWith(content)
- replaces each element in jq with contentjq.replaceAll(selector)
- replaces elements matching selector with elements in jq
Removing Elements
jq.empty()
- Remove all child elementsjq.remove([selector])
- Remove specific child elements- if no selector specified, removes all elements in jq
- if selector specified, removes only those that match selector
Hiding and Showing Elements
jq.hide()
- hide elementsjq.show()
- show elementsjq.toggle()
- show if hidden and hide if shown
There are also built in effects when hiding and showing.
jq.fadeIn()
jq.fadeOut()
jq.fadeTo(a specific opacity)
jq.slideDown() - shows
jq.slideUp() - hides
jq.slideToggle()
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.
jq.blur(handler);
- loses keyboard focusjq.change(handler);
- value for an input, textarea or select changesjq.click(handler);
- mouse clickjq.dblclick(handler);
- mouse double-clickjq.error(handler);
- an element such as img isn't loaded properlyjq.focus(handler);
- gains keyboard focusjq.keydown(handler);
- while element has keyboard focusjq.keypress(handler);
- while element has keyboard focusjq.keyup(handler);
- while element has keyboard focusjq.mousedown(handler);
- mouse button pressed while mouse cursor is over elementjq.mouseup(handler);
- mouse button released while mouse cursor is over elementjq.mouseenter(handler);
- mouse cursor enters element; doesn't bubble to ancestorsjq.mouseleave(handler);
- mouse cursor leaves element; doesn't bubble to ancestorsjq.mouseout(handler);
- mouse cursor leaves element; bubbles to ancestorsjq.mouseover(handler);
- mouse cursor enters element; bubbles to ancestorsjq.mousemove(handler);
- mouse cursor moves inside elementjq.resize(handler);
- window is resizedjq.scroll(handler);
- element scroll position changesjq.select(handler);
- text in an input or textarea is selectedjq.submit(handler);
- form is submitted; return false in handler to cancel submit
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
- [1] jQuery Home Page
http://jquery.com - [2] The jQuery API
http://api.jquery.com - [3] Blog from jQuery creator John Resig
http://ejohn.org
Special thanks to Mark Volkmann for making this SETT article possible.