Jul 14, 2011

Automatically create a table of contents with jQuery

Recently, I had to create an FAQ page. A good FAQ should have a table of contents (TOC) at the start, easily allowing you to see the various section of the FAQ and the questions in each section. Naturally, I didn't want to have to maintain the TOC manually, every time a question/answer item had to be moved, added or deleted. On the server side, we didn't have a CMS in place (the project doesn't really require this, the FAQ is the only page with a TOC).

So, what to do? I could write scripts, running on the server, parsing a questions/answer file, generating the faq.html file out of that. Or I could use one of any number of other server-side tools. But since I had just started to get into jQuery, I decided to try something slightly different. Why not dynamically create the TOC and the numbering of the questions when the page is loaded? In other words, the HTML of the page would only contain questions and answers, but no TOC and no fixed numbering of the questions; all of that would be added dynamically in the browser when the page was displayed.

This seemed to be as good an exercise as any to try out my fledgling jQuery skills. Well, it works! Here is the JavaScript:



You can see the result here, in this extremely simple test page, which has no external dependencies, except the jQuery library. So, all you need can be seen in the source of that page. For illustration purposes, switch off JavaScript in your browser and reload the page. As you can see, it still looks readable, just the numbering and TOC is gone.

If you examine the page source, you can see a blob of jQuery in the ready() function, but no TOC. Instead, you have the questions and answers, following a particular structure. The jQuery code examines this structure and dynamically creates the TOC, the numbering of each entry and the links.

The structure you have to follow with your questions and answers is very simple:

A div with id "faq_toc" is where the TOC will be created. All top-level sections (or 'chapters') of the FAQ need to be enclosed in div elements with class "level_1_elem". In each of those sections, the individual questions and answers are enclosed in a simple div element. You can see that there are definitions for "level_1_link" and "qlink". These are the anchor tags, which allow linking to the individual answers and sections. These anchors do not contain any numbering - static or auto-generated. This means that even after you move questions around or add questions ahead of them, any links to those questions remain valid.

The result is a properly formatted TOC and numbered questions and answers, looking something like this:

This, I think, is not bad at all. No need to add a CMS or anything complicated on the server side, if the client can generate the TOC for us so nicely.

No comments:

Post a Comment