Hierarchical Table Of Contents Plugin For jQuery - jquery-toc.js

File Size: 5.58 KB
Views Total: 1140
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Hierarchical Table Of Contents Plugin For jQuery - jquery-toc.js

Yet another jQuery plugin for generating a hierarchical table of contents from headings within a specified container to improve the user experience on your content-heavy webpage.

The plugin generates navigation links in nested HTML lists that enables the user to quickly navigate between content sections on your long webpage.

To enable the TOC to smoothly scroll through your webpage, you might need a smooth scroll plugin.

How to use it:

1. Create an anchor link to toggle the table of contents.

<a id="toc">Open TOC</a>

2. Add unique IDs to the heading elements. If not specified, the plugin will automatically add 'toc-x' to the headings.

<h1 id="first">H1 Element</h1>
<h2>#toc-1</h2>
<h2>#toc-2</h2>
<h3>#toc-3</h3>
<h2 id="last">Last Heading</h2>

3. Place jQuery JavaScript library and the jquery-toc.js script at the bottom of the webpage.

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" 
        integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" 
        crossorigin="anonymous"></script>
<script src="jquery-toc.js"></script>

4. Call the function on the toc toggle link and done.

$('#toc').toc();

5. Specify the target container where the plugin looks for all the heading elements. Default: the whole body.

$('#toc').toc({
  container: $('.container')
});

6. Specify the heading elements. Default: 'h1, h2, h3'.

$('#toc').toc({
  selectors: 'h1, h2, h3, h4, h5'
});;

7. Decide whether or not to collapse the table of contents on init.

$('#toc').toc({
  status: true // expand the TOC on init
});;

8. Available callback functions whihc can be used to activate the toggle link.

$('#toc').toc({
  onOpen: function(list) {
    var $html = $('<div class="toc-wrapper"><p class="toc-title">Table of contents</p><div class="toc-list"></div></div>');

    $html.find('.toc-list').html(list);
    $('.content').before($html);

    $(this).text('Close TOC');
  },
  onClose: function() {
    $('.toc-wrapper').remove();
    $(this).text('Open TOC');
  }
});

9. Specify the list type you want to use.

$('#toc').toc({
  listTag: 'ul' // default: ol
});;

Changelog:

2018-07-13

  • Allows to use ordered or unordered list.
  • Handling xss

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