Table of Contents (TOC)

Generates a dynamic table of contents from headings inside one or more rich text blocks.

Pupolate a TOC from multiple rich text instances. Supports multiple independent TOCs via blx-id and now lists both H2 and H3, with proper indentation.

How it works

Gathers all H2 and H3 inside of [blx-el="toc-rich-text"].
Groups them in order they appear.
H3s become nested under their preceding H2, depending on the CSS added.
Each TOC instance only processes rich text blocks with a matching [blx-id="IDENTIFIER"].
Smooth scroll offset applies (100px by default).

1. Add Script

Add this <script> inside the before </body> tag of your page or project.

<script defer src="https://cdn.jsdelivr.net/gh/codeandwander/blx@v1.0.2/packages/toc/index.js"></script>

2. Add CSS

Add the CSS to the <head> or custom code inside the project.

[blx-el="toc-item"] a {
  text-decoration: none;
  color: inherit;
  transition: text-decoration-color 0.2s ease;
}

[blx-el="toc-item"] a:hover {
  text-decoration: underline;
  text-underline-offset: 2px;
}

/* Nested H3 style */
.toc-sublist {
  margin: 4px 0 0 16px;
  padding: 0;
  list-style: none;
}

.toc-sublist [blx-el="toc-item"] a {
  opacity: 0.8;
  font-size: 0.95em;
}

3. Add Required attributes

  • blx-el="toc" - add to the main TOC wrapper
  • blx-el="toc-list" - add to the <ul>
  • blx-el="toc-item" - add to the <li>
  • blx-el="toc-rich-text" - add to the rich text you want to use as sources, you can add multiple

Example HTML Structure

For the TOC add an empty <ul> and at least one <li> wrapped in a div. Add attributes to the three layers.
Add the source attributes to to each rich text you want to use as the source of the TOC.

<!-- Rich text source -->
<div blx-el="toc-rich-text" blx-id="sustainability" class="w-richtext">
  <h2>Section one</h2>
  <p>Content…</p>

  <h3>Subsection A</h3>
  <p>Content…</p>

  <h2>Section two</h2>
  <p>Content…</p>

  <h3>Subsection B</h3>
  <p>Content…</p>
</div>

<!-- TOC wrapper -->
<div blx-el="toc" blx-id="sustainability">
  <ul blx-el="toc-list">
    <li blx-el="toc-item" class="toc-item">
      <a href="#">Example heading</a>
    </li>
  </ul>
</div>

Additional Attributes

  • blx-id="IDENTIFIER" - optional, if using more then one TOC per page group all blx-el attributes by adding the same id to each one of them.