Highly Customizable Table Of Contents Generator – Tocbot

Category: Javascript , Menu & Navigation , Recommended | August 22, 2020
Author: tscanlin
Views Total: 776 views
Official Page: Go to website
Last Update: August 22, 2020
License: MIT


Highly Customizable Table Of Contents Generator – Tocbot


Tocbot is an easy yet highly customizable TOC (table of contents) generator created with pure JavaScript. It allows you to automatically generate an interactive in-page navigation menu from headling elements with support for scrollspy and smooth scroll.

Basic usage:

Install the Tocbot via NPM:

$ npm install tocbot --save

Import the necessary resources into your module.

import Tocbot from 'tocbot';

Alternatively, you can load the Tocbot’s files from a CDN.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.1.1/tocbot.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.1.1/tocbot.min.js"></script>

Add unique IDs to your headling elements within the document.

<div class="js-toc-content">
 <h1 id="1">Section 1</h1>
 <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur hendrerit euismod dui, nec fermentum urna porta ultrices. Nullam sed vestibulum purus, in auctor libero. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Maecenas dolor metus, molestie nec eros non, suscipit efficitur erat. Nulla ante odio, tristique sed nisi id, ultrices vulputate magna. Nunc congue nibh non lorem ultricies congue. Donec non metus vitae purus semper interdum eget a augue. Nullam sem ante, finibus eget sapien ultricies, pretium accumsan felis. Donec eget nulla orci.</p>
 <h2 id="2">Section 2</h2>
 <h2 id="3">Section 3</h2>

Create a container to place the generated table of contents.

<div class="js-toc"></div>

Initialize the Tocbot library and done.


Override the following options to customize the table of contents.


  // Where to render the table of contents.
  tocSelector: '.js-toc',

  // Where to grab the headings to build the table of contents.
  contentSelector: '.js-toc-content',

  // Which headings to grab inside of the contentSelector element.
  headingSelector: 'h1, h2, h3',

  // Headings that match the ignoreSelector will be skipped.
  ignoreSelector: '.js-toc-ignore',

  // For headings inside relative or absolute positioned containers within content
  hasInnerContainers: false,

  // Main class to add to links.
  linkClass: 'toc-link',

  // Extra classes to add to links.
  extraLinkClasses: '',

  // Class to add to active links,
  // the link corresponding to the top most heading on the page.
  activeLinkClass: 'is-active-link',

  // Main class to add to lists.
  listClass: 'toc-list',

  // Extra classes to add to lists.
  extraListClasses: '',

  // Class that gets added when a list should be collapsed.
  isCollapsedClass: 'is-collapsed',

  // Class that gets added when a list should be able
  // to be collapsed but isn't necessarily collpased.
  collapsibleClass: 'is-collapsible',

  // Class to add to list items.
  listItemClass: 'toc-list-item',

  // How many heading levels should not be collpased.
  // For example, number 6 will show everything since
  // there are only 6 heading levels and number 0 will collpase them all.
  // The sections that are hidden will open
  // and close as you scroll to headings within them.
  collapseDepth: 0,

  // Smooth scrolling enabled.
  scrollSmooth: true,

  // Smooth scroll duration.
  scrollSmoothDuration: 420,

  // Callback for scroll end.
  scrollEndCallback: function (e) { },

  // Headings offset between the headings and the top of the document (this is meant for minor adjustments).
  headingsOffset: 1,

  // Timeout between events firing to make sure it's
  // not too rapid (for performance reasons).
  throttleTimeout: 50,

  // Element to add the positionFixedClass to.
  positionFixedSelector: null,

  // Fixed position class to add to make sidebar fixed after scrolling
  // down past the fixedSidebarOffset.
  positionFixedClass: 'is-position-fixed',

  // fixedSidebarOffset can be any number but by default is set
  // to auto which sets the fixedSidebarOffset to the sidebar
  // element's offsetTop from the top of the document on init.
  fixedSidebarOffset: 'auto',

  // includeHtml can be set to true to include the HTML markup from the
  // heading node instead of just including the textContent.
  includeHtml: false,

  // orderedList can be set to false to generate unordered lists (ul)
  // instead of ordered lists (ol)
  orderedList: true,

  // If there is a fixed article scroll container, set to calculate titles' offset
  scrollContainer: null,

  // prevent ToC DOM rendering if it's already rendered by an external system
  skipRendering: false,

  // Optional callback to change heading labels. 
  // For example it can be used to cut down and put ellipses on multiline headings you deem too long.
  // Called each time a heading is parsed. Expects a string in return, the modified label to display.
  // function (string) => string
  headingLabelCallback: false,

  // ignore headings that are hidden in DOM
  ignoreHiddenElements: false,

  // Optional callback to modify properties of parsed headings.
  // The heading element is passed in node parameter and information parsed by default parser is provided in obj parameter.
  // Function has to return the same or modified obj. 
  // The heading will be excluded from TOC if nothing is returned.
  // function (object, HTMLElement) => object | void
  headingObjectCallback: null,

  // onclick function to apply to all links in toc. will be called with
  // the event as the first parameter, and this can be used to stop,
  // propagation, prevent default or perform action
  onClick: false

Refresh the Tocbot.


Destroy the Tocbot and remove the table of contents from DOM.



v4.12.0 (08/22/2020)

  • update

v4.10.0 (01/19/2020)

  • add options.headingObjectCallback allows better customization

You Might Be Interested In:

One thought on “Highly Customizable Table Of Contents Generator – Tocbot

  1. Νικόλαος Σμπαρούνης

    I am trying to add automatically update-able tables of contents (T.O.C.) to a large number of my extensive web documents, mostly engineering and political stuff. Since this covers many decades of work, it is entirely out of question to manually create content tables painstakingly from scratch.
    Searching for an automated solution on the Internet, I concluded that the most suitable solution was the Tocbot generator. I suppose that, whenever I manage to put it to work, it will create a text-box at a designated place, which will display hyperlinks to the various heading titles contained in the document.
    Although I am quite familiar with HTML and css, I am totally unfamiliar with JavaScript. I have never before attempted to insert any Java utility to my own creations, so I am obviously doing things wrong. The instructions I have found at various sites probably assume some user familiarity with embedding JavaScript, I may be too stupid to initiate the Tocbot. Some sources I discovered are:
    For reasons of clarity, I created a small demo sample of what I am trying to do , the file “sample.html” filling it with gibberish text. In case of problems with the attached file, it is also stored online at http://sbarounis.ucoz.com/TimePlanning/sample.html
    Now, what I want to do is to include as little code in each document itself as possible, for this reason I have taken the option of using the online Tocbot’s files from a CDN, if I am doing this right|

    Let me note that I included at the section some code that will apply multilevel numbering to the various heading categories (the blue labels in the text). I don’t know if these would be included in the T.O.C. in case I managed to get Tocbot working, but this would certainly be desirable.
    Afterwards, I put the intended piece of text within the …… for Tocbot to handle it.
    Then, according to the instruction I found, I Created a container to place the generated table of contents, placing it at the very end of the content, in order to locate it easily.

    It seems that the tricky part is that Initialize the Tocbot library command, “tocbot.init();”. I tried to put it at various places, before and after the tag, but nothing happened except from appearing within the text without rendering any T.O.C.
    What I googled for in vain was an actually published webpage utilizing Tocbot, that would show me directly how to place the various commands within my HTML code. Unfortunately, I was unable to locate any.


Leave a Reply