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?

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay