Using jQuery Script for Creating Dynamic Table of Contents

Packt Publishing

A typical jQuery script uses a wide assortment of the methods that the library offers. Selectors, DOM manipulation, event handling, and so forth come into play as required by the task at hand. In order to make the best use of jQuery, we need to keep in mind the wide range of capabilities it provides.

A Dynamic Table of Contents

As an example of jQuery in action, we'll build a small script that will dynamically extract the headings from an HTML document and assemble them into a table of contents for that page. Our table of contents will be nestled on the top right corner of the page:

We'll have it collapsed initially as shown above, but a click will expand it to full height:

At the same time, we'll add a feature to the main body text. The introduction of the text on the page will not be initially loaded, but when the user clicks on the word Introduction, the introductory text will be inserted in place from another file:

Before we reveal the script that performs these tasks, we should walk through the environment in which the script resides.

Obtaining jQuery

The official jQuery website (http://jquery.com/) is always the most up-to-date resource for code and news related to the library. To get started, we need a copy of jQuery, which can be downloaded right from the home page of the site. Several versions of jQuery may be available at any given moment; the latest uncompressed version will be most appropriate for us.

No installation is required for jQuery. To use jQuery, we just need to reside it on our site in a public location. Since JavaScript is an interpreted language, there is no compilation or build phase to worry about. Whenever we need a page to have jQuery available, we will simply refer to the file's location from the HTML document.

Setting Up the HTML Document

There are three sections to most examples of jQuery usage— the HTML document itself, CSS files to style it, and JavaScript files to act on it. For this example, we'll use a page containing the text of a book:

The actual layout of files on the server does not matter. References from one file to another just need to be adjusted to match the organization we choose. In most examples in this book, we will use relative paths to reference files (../images/foo.png) rather than absolute paths (/images/foo.png).This will allow the code to run locally without the need for a web server.

The stylesheet is loaded immediately after the standard <head> elements. Here are the portions of the stylesheet that affect our dynamic elements:

After the stylesheet is referenced, the JavaScript files are included. It is important that the script tag for the jQuery library be placed before the tag for our custom scripts; otherwise, the jQuery framework will not be available when our code attempts to reference it.

Writing the jQuery Code

Our custom code will go in the second, currently empty, JavaScript file which we included from the HTML using <scriptsrc="dolittle.js"type="text/javascript"></script>. Despite how much it accomplishes, the script is fairly short:

We now have a dynamic table of contents that brings users to the relevant portion of the text, and an introduction that is loaded on demand.

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.

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 finding an element:

$('#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')

ere we produce a jQuery object potentially referring to many elements. 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 complex as we need.

DOM Traversal Methods

Sometimes we have a jQuery object that already references a set of DOM elements, 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 instead to a DOM element). In our case, this jQuery object is in turn pointing to the <h3> heading of the table of contents. The .toggleClass method call manipulates this heading element. The subsequent .next() operation changes the element we are working with, though, so that the following .slideToggle method call acts on the <div> containing the table of contents rather than its header.

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:

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 heading 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.

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:

In this snippet we register a handler that will execute each time the selected anchor tag is clicked. The click event is one of the most common ones observed, but there are many others.

There is also 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 this 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.

AJAX Methods

Many modern websites 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:

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.

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 matched elements. 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.

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 the use for a plug-in:

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 h3').click(function() { $(this).toggleNext();});

Whenever code could be reused outside the current script, it might do well as a plug-in.

Summary

We've now seen a complete, functional jQuery-powered script. This example, though small, brings a significant amount of interactivity and usability to the page. The script has illustrated the major types of tools offered by jQuery, as well. We've observed how the script finds items in the DOM and changes them as necessary. We've witnessed response to user action, and animation to give feedback to the user after the action. We've even seen how to pull information from the server without a page refresh, and how to teach jQuery brand new tricks in the form of plug-ins.

Alerts & Offers

Series & Level

We understand your time is important. Uniquely amongst the major publishers, we seek to develop and publish the broadest range of learning and information products on each technology. Every Packt product delivers a specific learning pathway, broadly defined by the Series type. This structured approach enables you to select the pathway which best suits your knowledge level, learning style and task objectives.

Learning

As a new user, these step-by-step tutorial guides will give you all the practical skills necessary to become competent and efficient.

Beginner's Guide

Friendly, informal tutorials that provide a practical introduction using examples, activities, and challenges.

Essentials

Fast paced, concentrated introductions showing the quickest way to put the tool to work in the real world.

Cookbook

A collection of practical self-contained recipes that all users of the technology will find useful for building more powerful and reliable systems.

Blueprints

Guides you through the most common types of project you'll encounter, giving you end-to-end guidance on how to build your specific solution quickly and reliably.

Mastering

Take your skills to the next level with advanced tutorials that will give you confidence to master the tool's most powerful features.

Starting

Accessible to readers adopting the topic, these titles get you into the tool or technology so that you can become an effective user.

Progressing

Building on core skills you already have, these titles share solutions and expertise so you become a highly productive power user.