Automatic Table of Contents with jQuery - Autocontents.js

File Size: 4.01 KB
Views Total: 239
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Automatic Table of Contents with jQuery - Autocontents.js

Autocontents.js is a super tiny jQuery plugin that automatically generates a nested table of contents for any element on a web page based on heading tags. 

The plugin works by first identifying all heading elements, including h1, h2, h3, etc., within a specified container. It then dynamically builds a table of contents containing the text of each heading. Headings are nested under each other in the TOC based on their level for visual hierarchy. The resulting list contains hyperlinks that allow visitors to scroll the page to any part of the content.

See Also:

How to use it:

1. Download and put the jquery.autocontents.js script after jQuery library.

<script src="/path/to/cdn/jquery.slim.min.js"></script>
<script src="/path/to/jquery.autocontents.js"></script>

2. Create an empty DIV element where you want to place the table of contents.

<div class="autoContents">
  <!-- table of contents will be auto inserted here -->
</div>

3. Call the function on the target container from which the plugin scans h1-h6 tags and builds a clean, nested list of links.

<div class="content">
  <h1>...</h1>
  ...
  <h2>...</h2>
  ...
  <h3>...</h3>
  ...
</div>
$(document).ready(function(){
  $('.content').autoContents({
    contentsElement: $('.autoContents')
  });
});

4. Apply your own CSS styles to the table of contents.

.autoContents ul {
  ...
}

.autoContents ul li {
  ...
}

This awesome jQuery plugin is developed by jeremyblaze. For more Advanced Usages, please check the demo page or visit the official website.