Automatic Table of Contents Built with Javascript

Any long page of content with distinct and well marked up content can benefit from a table to contents. A table of contents provides a quick way to jump down the page to the desired section. Of course you can create a table of contents manually, but it may be smart to build it dynamically on-the-fly with JavaScript. This is true for several reasons:

  • It’s easier – write the JavaScript once and it can create the Table on Contents on every page you need it.
  • It’s more reliable – the JavaScript isn’t subject to authoring errors.
  • 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.

This kind of thing has been done many times and many ways. But this time is ours! Plus it makes for a good tutorial.

A live example of this can be found on CodePen’s PRO feature pages like this one for Professor Mode.

HTML: Headers and IDs

A long page of different parts you wish to link to could be marked up a bunch of ways. Perhaps a FAQ page could be a <dl>. It could literally be <section> after<section>. In our case, we’ll assume this structure:

<article>

   <h3 id="question-one">Title of Question</h3>
   <!-- whatever other content, probably some paragraphs and stuff. -->

   <h3 id="question-two">Another Question</h3>
   <!-- whatever other content, probably some paragraphs and stuff. -->

   <!-- etc -->

</article>

A perfectly legit page full of headers with IDs and the content between them. Note the ID’s. They are unique, as any good ID ought to be. This is required because it gives us a link target.

A link like this:

<a href="#question-one">Link to Question One</a>

Will jump down the page when clicked until the element with the ID “question-one” is in view.

Building the Table of Contents with jQuery

Our goal is to inject HTML on the page in the form of a table of contents. Like this:

<nav role="navigation" class="table-of-contents">
  <h2>On this page:</h2>
  <ul>
    <li><a href="#question-one">Question One</a></li>
  </ul>
</nav>

A list in that <nav>Yep.

Read full article here: Automatic Table of Contents | CSS-Tricks.