DEV Community

Aellon
Aellon

Posted on

Automagic Table of Contents

Imagine visiting a website with seemingly endless scrolling. You could easily get lost in a sea of content, but I won't let that happen. Table of contents to the rescue! I will examine three approaches below.

Quick Way (not recommended)

Hardcoding a table of contents at the top of every page of content
This wouldn't be very DRY. It's an easy solution to get something working right away, but it could be time consuming in the long run. What if you need to add a table of contents to 100 pages, or what if a client is entering content? That would be a lot of copying and pasting, and a lot of room for error.

Better Way

Table of contents that is generated dynamically
This way uses some jQuery to generate the table of contents automatically. It will get the text from every <h2> element and generate a table of contents with links to those headings. CSS-Tricks has a really nice demo for this.

Best Way

Table of contents that is generated dynamically and highlights which section you're in
This takes the better way and adds some automagical flair to it. The table of contents will be hidden at first, to show a banner image or keep the navigation menu minimal. Then upon scrolling, the table of contents will appear, fixed to the top of the page. As you scroll down it will underline the section you're in.

The last approach may not be a good fit for every project, but it is my favorite for a long page of content. How would you add a table of contents?

Top comments (0)