Categories: CSSScriptWeb Design

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.

Table of Contents

Toggle

Basic usage:

Install the Tocbot via NPM:

# 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>
 ...
</div>

Create a container to place the generated table of contents.

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

Initialize the Tocbot library and done.

tocbot.init();

Override the following options to customize the table of contents.

tocbot.init({

  // 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,

  // Set the base path, useful if you use a `base` tag in `head`.
  basePath: '',

  // Only takes affect when `tocSelector` is scrolling,
  // keep the toc scroll position in sync with the content.
  disableTocScrollSync: false,

  // If this is null then just use `tocElement` or `tocSelector` instead
  // assuming `disableTocScrollSync` is set to false. This allows for
  // scrolling an outer element (like a nav panel w/ search) containing the toc.
  // Please pass an element, not a selector here.
  tocScrollingWrapper: null,

  // Offset for the toc scroll (top) position when scrolling the page.
  // Only effective if `disableTocScrollSync` is false.
  tocScrollOffset: 0,

  // Enable the URL hash to update with the proper heading ID as
  // a user scrolls the page.
  enableUrlHashUpdateOnScroll: false
  
});

Refresh the Tocbot.

tocbot.refresh()

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

tocbot.destroy()

Changelog:

v4.36.3 (05/05/2025)

  • fix for global vars caused by certain ids causing issues with init

v4.36.2 (04/05/2025)

  • update

v4.36.0 (04/04/2025)

  • update

v4.35.3 (03/21/2025)

  • update

v4.35.2 (03/14/2025)

  • fix highlight issue after clicking and scrolling to the bottom

v4.35.1 (03/13/2025)

  • switch to getByElementId to fix encoding edge case

v4.35.0 (02/12/2025)

  • Upgrade sass

v4.34.1 (02/11/2025)

  • update sass and fix deprecation warnings

v4.34.0 (02/10/2025)

  • bugfixes

v4.33.0 (01/31/2025)

  • update and bugfix

v4.32.2 (11/09/2024)

  • update to simplify scroll sync behavior
  • bugfix

v4.31.0 (10/14/2024)

  • add option for toc scroll wrapper to be set to another element

v4.30.0 (09/26/2024)

  • Scroll sync helper

v4.29.0 (08/09/2024)

  • bugfix

v4.28.2 (05/23/2024)

  • update

v4.28.0 (05/21/2024)

  • add a server render util

v4.27.20 (05/08/2024)

  • update

v4.27.19 (05/03/2024)

  • add types to files array (Tim Scanlin)

v4.27.18 (05/01/2024)

  • update

v4.27.13 (04/25/2024)

  • update

v4.23.0 (11/23/2023)

  • bugfix

v4.22.0 (11/13/2023)

  • classname adding optimization

v4.21.6 (11/01/2023)

  • Update

v4.21.2 (10/06/2023)

  • Fix for skipRendering option

v4.21.0 (04/25/2023)

  • update

v4.12.0 (08/22/2020)

  • update

v4.10.0 (01/19/2020)

  • add options.headingObjectCallback allows better customization

The post Highly Customizable Table Of Contents Generator – Tocbot appeared first on CSS Script.

rssfeeds-admin

Share
Published by
rssfeeds-admin

Recent Posts

Michigan lawmakers push bill banning Chinese connected vehicles in U.S. market

WASHINGTON, DC (WOWO) Michigan members of Congress have introduced bipartisan legislation aimed at prohibiting the…

12 minutes ago

OpenAI Confirms Security Breach Via TanStack npm Supply Chain Attack

Two employee devices at OpenAI were compromised in a sweeping software supply chain attack targeting…

12 minutes ago

Cisco Catalyst SD-WAN Controller 0-Day Actively Exploited to Gain Admin Access

A maximum-severity zero-day vulnerability in Cisco Catalyst SD-WAN Controller is being actively exploited in the…

12 minutes ago

An Outpouring of Frustration Over Pennsylvania’s Rapid Data Center Growth

This article originally appeared on Inside Climate News, a nonprofit, non-partisan news organization that covers…

18 minutes ago

Three Indianapolis USPS workers charged in theft of cell phones and Super Bowl ring

INDIANAPOLIS, IND. (WOWO) Three employees with the United States Postal Service are facing felony charges…

22 minutes ago

Indiana enacts statewide “bell-to-bell” cellphone ban in schools starting July 1

INDIANAPOLIS, IND. (WOWO) Indiana schools will be required to enforce stricter student cellphone restrictions beginning…

22 minutes ago

This website uses cookies.