Basic Table Of Contents Generator In JavaScript – table-of-contents.js

Category: Javascript , Menu & Navigation | April 2, 2020
Author:cferdinandi
Views Total:2,927 views
Official Page:Go to website
Last Update:April 2, 2020
License:MIT

Preview:

Basic Table Of Contents Generator In JavaScript – table-of-contents.js

Description:

A really simple table of contents generator to create a hierarchical in-page navigation list from heading elements found within the document.

How to use it:

1. Create a container in which the plugin generates a table of contents for your web content.

<div data-toc></div>

2. Wrap your content into a container with the data-content attribute.

<div data-content>
  <h2>Heading 1</h2>
  <p>Content</p>
  <h3>Heading 1-1</h3>
  <p>Content</p>
  <h4>Heading 1-1-1</h4>
  <p>Content</p>
  <h2>Heading 2</h2>
  <p>Content</p>
  ...
</div>

3. Download and load the main script table-of-contents.js in the document.

<script src="table-of-contents.js"></script>

4. The JavaScript to generate a basic table of contents.

tableOfContents('[data-toc]', '[data-content]');

5. The plugin automatically extracts content from heading elements and insert them into the anchor links. To customize the anchor name, assign a unique ID to your heading element as follows:

<h2 id="custom-anchor">Heading 1</h2>

6. Customize the list type used to place the anchor links. Default: unordered list.

tableOfContents('[data-toc]', '[data-content]',{
  listType: 'ol'
});

7. Customize the header of the table of contents.

tableOfContents('[data-toc]', '[data-content]',{
  heading: 'Table of Contents',
  headingLevel: 'h2'
});

8. Customize the heading levels from which the plugin generates a table of contents.

tableOfContents('[data-toc]', '[data-content]',{
  levels: 'h2, h3, h4, h5, h6'
});

You Might Be Interested In:


Leave a Reply