Minimal Table of Contents Generator In JavaScript – Tocbase

Category: Javascript , Menu & Navigation | September 17, 2022
Author:ashutoshbw
Views Total:127 views
Official Page:Go to website
Last Update:September 17, 2022
License:MIT

Preview:

Minimal Table of Contents Generator In JavaScript – Tocbase

Description:

Tocbase is a minimal JavaScript ToC library for generating an HTML list-based table of contents from heading elements with unique IDs.

Features:

  • Automatically generates ids of headings.
  • Smartly adds indentation to numbered ToC items.
  • Automatically adds anchor links to headings.
  • Easy to style using your own CSS.

How to use it:

1. Load the necessary JavaScript libraries in the document.

<!-- Core -->
<script src="https://www.unpkg.com/[email protected]/dist/cdn.umd.min.js"></script>
<!-- A plugin for automatically generating ids of headings. -->
<script src="https://www.unpkg.com/[email protected]/dist/cdn.umd.min.js"></script>
<!-- A plugin for smartly adding indentation to numbered ToC items. -->
<script src="https://www.unpkg.com/tocbase-pl[email protected]/dist/cdn.umd.min.js"></script>

2. Create an empty element to hold the table of contents.

<p id="toc">
</p>

3. Add a unique ID to each heading in the document.

<h2 id="level-1">Level 1</h2>
<h3 id="level-1-1">Level 1-1</h3>
<h3 id="level-1-2">Level 1-2</h2>
<h2 id="level-2">Level 2</h2>
...

4. Apply your own CSS styles to the ToC items.

#TOC li {
  list-style: none;
}
#TOC ul {
  padding-left: 1.3em;
}
#TOC > ul {
  padding-left: 0;
}
#TOC a:not(:hover) {
  text-decoration: none;
}

5. Initialize the Tocbase.

tocbase({
  config: {
    titleText: "Table of Contents",
    num: 1,
    hNum: 1,
    anchor: 1,
    anchorSymbol: "#",
    cH: "toc-h",
    cRootUl: "toc-root-ul",
    cTocNum: "toc-num",
    cHAnchor: "h-anchor",
    cHNum: "h-num",
    cToc: "toc",
  },
  omit: "h1",
  placeholderID: "toc",
  plugins: [
    autoID(),
    smartIndent(),
  ],
});

Changelog:

v8.4.5 (09/17/2022)

  • Bugfix

v8.3.4 (09/16/2022)

  • API update: bag.list to bag.lists for better understandability.

You Might Be Interested In:


Leave a Reply