JTFDI Library
just the focus do it    •    
Creator Economy
       •       
Media
       •       
Marketing
       •       
Eating & Drinking
       •       
Commerce
       •       
Customer Relationships
       •       
Reading
       •       
Tech-stack
       •       
Productivity
       •       
Startup
       •       
Technology
       •       
Business
       •       
•    just the focus do it    •     just the focus do it    
Docs
Mag
Writing
Blog
Try it for Free

Dynamically Generated ToC with Webflow CMS

2023-04-15
, most recent update.

Generating a Table of Contents (TOC) with Richtext Headings as Anchor Text

I have improved the Table of Contents (TOC) being generated, from the flowrite example (vide infra/ see below). The improvement modifies the script to use the heading text string as the unique ID, no longer just an index number.

This

  1. Makes it clear to readers of the link where they are being pointed to
  2. Could improve the search engine findability (SEO)

New Code Snippet

document.getElementById("content").querySelectorAll("h2,h3,h4").forEach(function(heading) {
  let headingText = heading.innerHTML.trim().toLowerCase();
  headingText = headingText.replace(/[^a-z0-9\s]+/gi, '').replace(/\s+/g, '-'); // Remove non-alphabetic characters and replace spaces with hyphens
  heading.setAttribute("id", headingText); // Set the unique ID as the heading text

const item = document.createElement("a"); item.innerHTML = heading.innerHTML; item.setAttribute("class", "tocitem"); item.setAttribute("href", "#" + headingText); // Set the href attribute to the heading text as the unique ID document.querySelector("#toc").appendChild(item); });

Before

  1. For each of the h2 and h3 elements found, it assigned a unique ID in the format "toc-N", where N is the index number of the element in the query result.
  2. It then created an anchor element () for each heading, and set the innerHTML to be the same as the heading text.

Now, improved

This JavaScript code generates a table of contents (TOC) for a webpage by creating anchor links for all h2, h3, and h4 heading elements within an element with the ID "content".

  1. Iterates through each of the selected heading elements using the forEach loop.

  2. Trims leading and trailing whitespace from the heading text and converts it to lowercase.

    1. Removes any non-alphanumeric characters (except spaces) from the heading text using the regular expression /[^a-z0-9\s]+/gi. This ensures that the heading text contains only lowercase letters, numbers, and spaces.
    2. Replaces any sequence of one or more spaces in the heading text with a single hyphen using the regular expression /\s+/g. This step creates a unique ID that consists of words separated by hyphens.
  3. Assigns the resulting heading text as the unique ID of the heading element.

  4. Creates an anchor element () and sets its innerHTML to the heading text.

When this script is executed, it generates a table of contents with clickable links pointing to the respective heading elements (h2, h3, and h4) within the "content" element.

</ hr>

How-to Implement

Generating ToC’s based on h2 and h3 headings of a rich text CMS element with active states in a sticky Table of Contents, as done by flowrite.

Follow the flowriteinstructions. This post here is just archival for my implementations of it. Besides specifics, they also talk about variants like how to create ToC inside a rich text element.

Create a Div with id "toc" for the ToC with a text-link element inside.

Style the TOC classes.

Style the "active" class.

Name the Rich Text content element id "content".

Create custom field in CMS Collection:

TOC generated from

(Plain text)

Comma separated, no spaces! Define the Heading tags you want to be generated in the ToC from the Rich Text

Insert code at the end of <\body> tag on collection page template setting.

Use the dynamic “Add Field” to replace [HEADINGS] in above code with the value of your "TOC generated from" CMS field.

Read next in DOCU

Optimize Netlify Build Minutes and DecapCMS by Skipping Unnecessary Builds

Optimize Netlify Build Minutes and DecapCMS by Skipping Unnecessary Builds

Read next in DOCU

Displaying Both the Publication and Update Dates on Webpages

Showing both the update and the publish date on your blog / web page seems to be difficult for Search Engines and therefore it seems like only displaying “last updated” is the safer way. If your blog shows more than one date, you are probably confusing Google.

Read next in DOCU

Localization: The "hreflang" Tag Accross Different Domains

John Mueller on how to use the hreflang tags across domains for the localization schemas: It doesn't matter if it's all on one domain or across multiple domains. It should just be one clear place per country and language.

Read next in DOCU

DecapCMS Markdown Guide: Handling URLs with Parentheses for Text Fragment Highlighting

Are broken links in your DecapCMS Markdown articles giving you a headache? never let parentheses break your links again: handle text fragment highlighting in Markdown. No more parentheses-induced troubles in your Github articles built with Netlify!

Read next in DOCU

Leveraging a Small JavaScript for a Quick Multilingual Strategy in Webflow

A button that appears when there is an alternate language defined for your content, making your cotent more relevant to your users experiences. Implementing a Dynamic Language Switcher Button with JavaScript

Read next in DOCU

Interactive URL Copy Feature in Webflow Using Clean JavaScript and Clipboard API

An interactive URL copy feature in Webflow. Using clean JavaScript and the powerful Clipboard API, making it easier for visitors to share your pages. Because who doesn’t appreciate a great user experience?

Read next in DOCU

An Extensive Dynamic Table of Contents Generator for Webflow CMS

Boost your Webflow Blog's readability and SEO with a dynamic Table of Contents (ToC) generator. It automatically creates a stylable, navigable ToC from your headings, and enhances user experience by highlighting the active section during scrolling.

Read next in DOCU

Styling Our Auto-Generated ToC in Webflow

Read next in DOCU

Creating or Changing Slugs in DecapCMS (formerly Netlify CMS)

Changing the URL Slug of your post in DecapCMS in config.yaml using the slug key and name key

Read next in DOCU

Smooth Scrolling to the Next Section with JavaScript and [foo](#next) markdown syntax

When I write [[`foo`](#next)`](#next)` markdown syntax in my content I want the reader to jump to the next section, the next anchor, on my webpage.

Read next in DOCU

Vimeo vs YouTube Embed for your Website

Consider this when you decide between YouTube or Vimeo for Website embeds

Read next in DOCU

Editorial Workflow in Decap CMs (formerly Netlify CMS)

Read next in DOCU

README for ChatGPT and How to Write the Best Prompts

When answering prompts, does it help ChatGPT to be more specific and precise if you give it a set of definitions upfront?

Read next in DOCU

Use Hash-symbol vs Triple-quotes Syntax for Commenting Python Code

Consider this when you choose the syntax for commenting code in Python

Read next in DOCU

Dynamically Generated ToC with Webflow CMS

Generating ToC’s based on h2 and h3 headings of a rich text CMS element with active states in a sticky Table of Contents

Read next in DOCU

Dynamic Social Media Share Buttons for Webflow CMS Blogposts

Add a Twitter button and a share on LinkedIn to your blogposts with sharing content generated from Webflow CMS

Read next in DOCU

Calculate Read Time from Webflow CMS

Calculated a read time from Webflow CMS and add to your blog template.

Read next in DOCU

Add Copy-able Code Blocks to Webflow CMS

Uses highlight.js and custom code to add code blocks where you can copy the code to rich text element of Webflow CMS

Hej. I am on Twitter, too.

Connect with me on Twitter and LinkedIn.