Skip to content

oom-components/toc

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Table of contents

Web component to create a table of contents.

  • No dependencies
  • Very light
  • Follow the progressive enhancement strategy. If JavaScript fails the page continue working.
  • No styles or themes are provided with this package.
  • Build with modern JavaScript.

Usage

Import and register the component with the desired tag name:

import Toc from "toc/toc.js";

customElements.define("oom-toc", Toc);

Use it in the HTML code. The data-target attribute must contain the id of the text container:

<nav>
  <h2>Table of contents</h2>

  <oom-toc data-target="main-content">
    Fallback text if something fails
  </oom-toc>
</nav>

<div id="main-content">
  <h2>Lorem Ipsum Dolor Sit Amet</h2>
  ...
  <h3>Consectetur Adipiscing</h3>
  ...
</div>

Anchors

Anchors are created automatically if they are missing. For example:

<h2>One</h2>
<h2 id="two">Two</h2>
<h2><a id="three" href="#three">Three</a></h2>

The component makes the following changes:

<h2 id="one"><a href="one">One</a></h2>
<h2 id="two"><a href="two">Two</a></h2>
<h2><a id="three" href="#three">Three</a></h2>
  • It creates the id automatically using the text content of the heading.
  • It creates the anchor automatically if it's missing
  • If the id and/or anchor is detected, it does nothing.

If you want a different anchor style, you can override the anchorCreator static property:

import Toc from "toc/toc.js";

// <h2><a href="#id">anchor</a>Header</h2>
Toc.anchorCreator = (heading, id) => {
  const a = document.createElement("a");
  a.href = `#${id}`;
  a.innerHTML = "anchor";
  heading.prepend(a);
};

customElements.define("oom-toc", Toc);

About

Web component to create a table of content

Resources

License

Stars

Watchers

Forks