Automatic Toc Tree Generator With jQuery - Autoc.js

Automatic Toc Tree Generator With jQuery - Autoc.js
File Size: 65.4 KB
Views Total: 71
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   

A lightweight table of contents generator jQuery plugin that automatically generates a TOC tree based on heading elements found within the document.

How to use it:

1. Load the minified version of the jQuery Autoc.js plugin after jQuery.

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

2. Create a container to hold the TOC tree.

<div id="toc"></div>
<h2 class="h2">Title1</h2>
  <h3 class="h3">Sub Title 1</h3>
    <div>Contents 1</div>
  <h3 class="h3">Sub Title 2</h3>
    <div>Contents 2</div>

<h2 class="h2">Title 2</h2>
  <h3 class="h3">Sub Title 1</h3>
    <div>Contents 1</div>
  <h3 class="h4">Sub Title 2</h3>
    <div>Contents 2</div>

...

3. Initialize the plugin to generate a basic TOC tree inside the container element you just created.

$.fn.autoc({ 
  id: 'toc'
});

4. The HTML structure of the generated TOC tree should look as follows.

<div id="toc">
  <div class="mx-auto">
    <h2 class="h2">Index</h2>
    <ul class="list-group">
      <li class="list-group-item" style="padding-left: 20px;"><a href="#header_1">Title1</a></li>
      <li class="list-group-item" style="padding-left: 40px;"><a href="#header_2">Sub Title1</a></li>
      <li class="list-group-item" style="padding-left: 40px;"><a href="#header_3">Sub Title2</a></li>
      <li class="list-group-item" style="padding-left: 20px;"><a href="#header_4">Title2</a></li>
      <li class="list-group-item" style="padding-left: 40px;"><a href="#header_5">Sub Title1</a></li>
      <li class="list-group-item" style="padding-left: 40px;"><a href="#header_6">Sub Title2</a></li>
    </ul>
  </div>
</div>

5. By default, the plugin uses Bootstrap's CSS to style the TOC tree. Feel free to override the default list classes to create your own styles.

$.fn.autoc({ 
  level: {
    1: { css: { paddingLeft: '0px' }, },
    2: { css: { paddingLeft: '20px' }, },
    3: { css: { paddingLeft: '40px' }, },
    4: { css: { paddingLeft: '60px' }, },
    5: { css: { paddingLeft: '80px' }, },
  },
  base: {
    class: ['mx-auto'],
    tag: 'div',
  },
  a: {
    class: [],
    css: {},
  },
  ul: { 
    class: ['list-group'] 
  },
  li: { 
    class: ['list-group-item'] 
  }
});

6. Customize the title of the TOC tree.

$.fn.autoc({ 
  title: {
    label: 'Index',
    tag: 'h2',
    class: ['h2']
  }
});

7. Set the start and end level of the heading elements.

$.fn.autoc({ 

  // h2
  start: 2,
  
  // h3
  end: 3
  
});

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