File Under: JavaScript

How to Dynamically Generate a Table of Contents

One of the great things about structured content like HTML is that you can manipulate the structure to generate little extras like a list of links or a table of contents. With long form writing making something of a comeback in the last year or so, we’ve started to notice more tables of contents on the web, offering a quick way to jump down the page to the sections you want to read. Check out developer Steve Losh’s blog for a great example of a table of contents.

Some sites no doubt generate their TOCs by hand, or assemble them server-side somewhere in the CMS, but building a table of contents doesn’t need to be complex or low level. In fact, so long as your HTML is well structured, you can easily generate a table of contents on the fly, using JavaScript.

Chris Coyier, of CSS-Tricks fame, recently posted a nice tutorial walking you through the process of creating a table of contents like the one used on Coyier’s CodePen site. The tutorial uses jQuery, but, with a little tinkering, you should be able to adapt the code to work with your favorite JavaScript library (or no library at all).

Here’s Coyier’s take on the benefits of using a dynamically generated table of contents:

  1. It’s easier – write the JavaScript once and it can create the table of contents on every page you need it.
  2. It’s more reliable – the JavaScript isn’t subject to authoring errors.
  3. It’s still accessible – A table of contents is good for the general concept of accessibility, but it is a bonus (not having it doesn’t ruin the page) and nearly all screen readers run JavaScript.

For all the code, and a detailed explanation of what’s going on, head on over to CSS-Tricks.