DEV Community

Aellon
Aellon

Posted on

3 1

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?

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay