Using jQuery Script for Creating Dynamic Table of Contents

Exclusive offer: get 50% off this eBook here
jQuery Reference Guide

jQuery Reference Guide — Save 50%

A Comprehensive Exploration of the Popular JavaScript Library

$23.99    $12.00
by Jonathan Chaffer Karl Swedberg | October 2007 | AJAX Open Source Web Development

This article by Karl Swedberg and Jonathan Chaffer, shows the basic categories of jQuery methods, and how they come into play within a jQuery script. To examine how the different aspects of jQuery are utilized, we will 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.

 

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:

Using jQuery Script for Creating Dynamic Table of Contents

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

Using jQuery Script for Creating Dynamic Table of Contents

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:

Using jQuery Script for Creating Dynamic Table of Contents

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:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
      <meta http-equiv="Content-Type" content="text/html;
                                                   charset=utf-8"/>
      <title>Doctor Dolittle</title>
    <link rel="stylesheet" href="dolittle.css" type="text/css" />
      <script src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="jquery.js" type="text/javascript"></script>
      <script src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="dolittle.js" type="text/javascript"></script>
  </head>
  <body>
    <div id="container">
      <h1>Doctor Dolittle</h1>
      <div class="author">by Hugh Lofting</div>
      <div id="introduction">
        <h2><a href="introduction.html">Introduction</a></h2>
      </div>
      <div id="content">
        <h2>Puddleby</h2>
        <p>ONCE upon a time, many years ago when our grandfathers
           were little children--there was a doctor; and his name was
           Dolittle-- John Dolittle, M.D.  &quot;M.D.&quot; means
           that he was a proper doctor and knew a whole lot.
       </p>

           <!-- More text follows... -->

      </div>
    </div>
  </body>
</html>

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:

/* -----------------------------------
   Page Table of Contents
-------------------------------------- */
#page-contents {
  position: absolute;
  text-align: left;
  top: 0;
  right: 0;
  width: 15em;
  border: 1px solid #ccc;
  border-top-width: 0;
  border-right-width: 0;
  background-color: #e3e3e3;
}
#page-contents h3 {
  margin: 0;
  padding: .25em .5em .25em 15px;
  background: url(arrow-right.gif) no-repeat 0 2px;
  font-size: 1.1em;
  cursor: pointer;
}
#page-contents h3.arrow-down {
  background-image: url(arrow-down.gif);
}
#page-contents a {
  display: block;
  font-size: 1em;
  margin: .4em 0;
  font-weight: normal;
}
#page-contents div {
  padding: .25em .5em .5em; 
  display: none;
  background-color: #efefef;
}

/* -----------------------------------
   Introduction
-------------------------------------- */
.dedication {
  margin: 1em;
  text-align: center;
  border: 1px solid #555;
  padding: .5em;
}

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.

 

jQuery Reference Guide A Comprehensive Exploration of the Popular JavaScript Library
Published: July 2007
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

Writing the jQuery Code

Our custom code will go in the second, currently empty, JavaScript file which we included from the HTML using <script src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="dolittle.js"type="text/javascript"></script>. Despite how much it accomplishes, the script is fairly short:

jQuery.fn.toggleNext = function() {
  this.toggleClass('arrow-down')
    .next().slideToggle('fast');
};

$(document).ready(function() {
  $('<div id="page-contents"></div>')
    .prepend('<h3>Page Contents</h3>')
    .append('<div></div>')
    .prependTo('body');

  $('#content h2').each(function(index) {
    var $chapterTitle = $(this);
    var chapterId = 'chapter-' + (index + 1);
    $chapterTitle.attr('id', chapterId);
    $('<a></a>').text($chapterTitle.text())
      .attr({
        'title': 'Jump to ' + $chapterTitle.text(),
        'href': '#' + chapterId
      })
      .appendTo('#page-contents div');
  });
  
  $('#page-contents h3').click(function() {
    $(this).toggleNext();
  });

  $('#introduction > h2 a').click(function() {
    $('#introduction').load(this.href);
    return false;
  });
});

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.

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 web log:
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 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:

$chapterTitle.attr('id', chapterId);

Here we modify the ID of the matched element on the fly.

Sometimes the changes are further-reaching, on the other hand:

$('<div id="page-contents"></div>')
  .prepend('<h3>Page Contents</h3>')
  .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 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:

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

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

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:

jQuery.fn.toggleNext = function() {
  this.toggleClass('arrow-down')
    .next().slideToggle('fast');
};

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.

jQuery UI 1.7: The User Interface Library for jQuery Build highly interactive web applications with ready-to-use widgets from the jQuery User Interface library
Published: November 2009
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

About the Author :


Jonathan Chaffer

Jonathan Chaffer is a member of Rapid Development Group, a web development firm located in Grand Rapids, Michigan. His work there includes overseeing and implementing projects in a wide variety of technologies, with an emphasis in PHP, MySQL, and JavaScript. He also leads on-site training seminars on the jQuery framework for web developers.

In the open source community, he has been very active in the Drupal CMS project, which has adopted jQuery as its JavaScript framework of choice. He is the creator of the Content Construction Kit, a popular module for managing structured content on Drupal sites. He is also responsible for major overhauls of Drupal's menu system and developer API reference.

He lives in Grand Rapids with his wife, Jennifer.

Karl Swedberg

Karl Swedberg is a web developer at Fusionary Media in Grand Rapids, Michigan, where he spends much of his time making cool things happen with JavaScript. As a member of the jQuery team, he is responsible for maintaining the jQuery API site at api.jquery.com. He is also a member of jQuery's Board of Advisors and a presenter at workshops and conferences. When he isn't coding, he likes to hang out with his family, roast coffee in his garage, and exercise at the local CrossFit gym.

Books From Packt

Learning jQuery 1.3
Learning jQuery 1.3

jQuery 1.3 with PHP
jQuery 1.3 with PHP

AJAX and PHP: Building Modern Web Applications 2nd Edition
AJAX and PHP: Building Modern Web Applications 2nd Edition

Apache MyFaces 1.2 Web Application Development
Apache MyFaces 1.2 Web Application Development

Ext JS 3.0 Cookbook
Ext JS 3.0 Cookbook

Drupal 6 JavaScript and jQuery
Drupal 6 JavaScript and jQuery

Spring Persistence with Hibernate
Spring Persistence with Hibernate

jQuery UI 1.7: The User Interface Library for jQuery
jQuery UI 1.7: The User Interface Library for jQuery

 


 

 

Your rating: None Average: 3 (1 vote)

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
n
G
v
z
B
q
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software