
Script dissection
This script has been chosen specifically because it illustrates the widespread capabilities of the jQuery library. Now that we've seen the code as a whole, we can identify the categories of methods used therein.
Note
We will not discuss the operation of this script in much detail here, but a similar script is presented as a tutorial on the Learning jQuery blog: http://www.learningjquery.com/2007/06/automatic-page-contents.
Selector expressions
Before we can act on an HTML document, we need to locate the relevant portions. In our script, we sometimes use a simple approach to find an element as follows:
$('#introduction')
This expression creates a new jQuery object that references the element with the ID introduction
. On the other hand, sometimes we require a more intricate selector.
$('#introduction > h2 a')
Here we produce a jQuery object referring to potentially many elements. With this expression, elements are included if they are anchor tags that are descendants of <h2>
elements, which are themselves children of an element with the ID introduction
.
These selector expressions can be as simple or as complex as we need. Chapter 2, Selector Expressions, will enumerate all of the selectors available to us and how they can be combined.
DOM traversal methods
Sometimes we have a jQuery object that references a set of Document Object Model (DOM) elements already, but we need to perform an action on a different, related set of elements. In these cases, DOM traversal methods are useful. We can see this in part of our script:
this.toggleClass('arrow-down')
.next()
.slideToggle('fast');
Because of the context of this piece of code, the keyword this
refers to a jQuery object (it often refers to a DOM element, instead). In our case, this jQuery object is in turn pointing to the toggler
link of the table of contents. The .toggleClass()
method call manipulates this element. However, the subsequent .next()
operation changes the element we are working with, so that the following .slideToggle()
call acts on the <div>
containing the table of contents rather than its clicked link. The methods that allow us to freely move about the DOM tree like this are listed in Chapter 3, DOM Traversal Methods.
DOM manipulation methods
Finding elements is not enough; we want to be able to change them as well. Such changes can be as straightforward as changing a single attribute.
$chapterTitle.attr('id', chapterId);
Here we modify the ID of the matched element on the fly.
Sometimes the changes are further-reaching:
$('<div id="page-contents"></div>') .prepend('<a class="toggler" href="#">Page Contents</a>') .append('<div></div>') .prependTo('body');
This part of the script illustrates that the DOM manipulation methods can not only alter elements in place but also remove, shuffle, and insert them. These lines add a new link at the beginning of <div id="page-contents">
, insert another <div>
container at the end of it, and place the whole thing at the beginning of the document body. Chapter 4, DOM Manipulation Methods, will detail these and many more ways to modify the DOM tree.
Event methods
Even when we can modify the page at will, our pages will sit in place, unresponsive. We need event methods to react to user input, making our changes at the appropriate time.
$('#introduction > h2 a').click(function() { $('#introduction').load(this.href); return false; });
In this snippet we register a handler that will execute each time the selected link is clicked. The click event is one of the most common ones observed, but there are many others; the jQuery methods that interact with them are discussed in Chapter 5, Event Methods.
Chapter 5 also discusses a very special event method, .ready()
.
$(document).ready(function() { // ... });
This method allows us to register behavior that will occur immediately when the structure of the DOM is available to our code, even before the images have loaded.
Effect methods
The event methods allow us to react to user input; the effect methods let us do so with style. Instead of immediately hiding and showing elements, we can do so with an animation.
this.toggleClass('arrow-down')
.next()
.slideToggle('fast');
This method performs a fast-sliding transition on the element, alternately hiding and showing it with each invocation. The built-in effect methods are described in Chapter 6, Effect Methods, as is the way to create new ones.
AJAX methods
Many modern web sites employ techniques to load content when requested without a page refresh; jQuery allows us to accomplish this with ease. The AJAX methods initiate these content requests and allow us to monitor their progress.
$('#introduction > h2 a').click(function() {
$('#introduction').load(this.href);
return false;
});
Here the .load()
method allows us to get another HTML document from the server and insert it in the current document, all with one line of code. This and more sophisticated mechanisms of retrieving information from the server are listed in Chapter 7, AJAX Methods.
Miscellaneous methods
Some methods are harder to classify than others. The jQuery library incorporates several miscellaneous methods that serve as shorthand for common JavaScript idioms. Even basic tasks like iteration are simplified by jQuery.
$('#content h2').each(function(index) { // ... });
The .each()
method seen here steps through the matched elements in turn, performing the enclosed code on all of them. In this case, the method helps us to collect all of the headings on the page so that we can assemble a complete table of contents. More helper functions like this can be found in Chapter 8, Miscellaneous Methods.
A number of additional pieces of information are provided by jQuery as properties of its objects. These global and object properties are itemized in Chapter 9, jQuery Properties.
Plug-in API
We need not confine ourselves to built-in functionality, either. The plug-in API that is part of jQuery allows us to augment the capabilities already present with new ones that suit our needs. Even in the small script we've written here, we've found use for a plug-in.
jQuery.fn.toggleNext = function() { this.toggleClass('arrow-down') .next().slideToggle('fast'); return this; };
This code defines a new .toggleNext()
jQuery method that slides the following element open and shut. We can now call our new method later when needed.
$('#page-contents > a.toggler).click(function() { $(this).toggleNext(); return false; });
Whenever a code could be reused outside the current script, it might do well as a plug-in. Chapter 10, Plug-in API, will cover the plug-in API used to build these extensions.