Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Table of contents in Javascript

DZone's Guide to

Table of contents in Javascript

· Web Dev Zone ·
Free Resource

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

This is my week end project: a table of contents generator. Well, technically, it’s more like a two hour project interrupted four times over the course of a Saturday but I guess it still qualifies as a week end project.

I got tired of managing the table of contents of my documentations manually and in particular, of having to modify all the section numbers by hand whenever I moved things around. This short Javascript program now automatically takes care of it for me. Here is the quick documentation:

// A simple HTML "table of contents" generator.
//
// 1) Include toc.js in your HTML file:
//          <script type="text/javascript" src="toc.js"></script>
//
// 2) Call generateToc() in your onLoad() method:
//           <body onLoad="generateToc();">
//
// 3) Declare a div with the id "table-of-contents" where you want
// your table of contents:
//           <div id="table-of-contents"></div>
//
// 4) Put each of your sections in an <a> tag with class "section",
// specifying an "indent" representing the indentation of that section.
// Only the length of the indent matters, now its content. If no indent
// is found, a string of size 1 is the default.
//
// Example:
// <a class="section" name="Section 1">Section 1</a>
// <a class="section" indent=".." name="Section 1a">Section 1a</a>
// <a class="section" name="Section 2">Section 2</a>

This script now powers both testng.org and jcommander.org, go take a look there if you want to see what it looks like.

Ideas for potential improvements:

  • Make the numbering optional or configurable.
  • Have the script add CSS classes to the sections for easier styling (“section1″, “section2″, etc…), since the indenting is pretty crude right now.

 

From http://beust.com/weblog/2011/12/10/table-of-contents-in-javascript/

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}