tocbot

repository·master·Indexed 23 days ago

https://github.com/tscanlin/tocbot

A lightweight, dependency-free library for automatically generating a table of contents based on the heading structure of an HTML document. It features smooth scrolling, active link highlighting, and customizable configuration for selectors, styling, and scrolling behavior. Version 4.36.8.

Tokens
6.4K
Snippets
9
Records
25
Agent score
80%

What's inside tocbot

  1. Initialize Tocbot

    master

    To build a table of contents, call tocbot.init() with a configuration object.

    Important Requirements:

    • The document headings must have id attributes so the browser can jump to them via hashes.
    • Ensure the body is scrollable.
    • If your headings are inside relative or absolute positioned containers within the content area, set hasInnerContainers: true.
    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',
      // For headings inside relative or absolute positioned containers within content.
      hasInnerContainers: true,
    });
  2. Include Tocbot CSS

    master

    Tocbot requires CSS for expanding/collapsing groupings and basic styling. You can include it via CDN or import the SCSS files if using a preprocessor like Sass or PostCSS.

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.32.2/tocbot.css">
    @import 'tocbot/src/scss/tocbot';
  3. Initialize and use Tocbot

    master

    To use Tocbot, you must initialize it with an options object.

    Important Requirements:

    1. Heading IDs: All headings used in the TOC must have id attributes so the browser can jump to them. Some markdown libraries (like showdown.js) do this automatically, while others (like marked) may require configuration.
    2. Scrollability: The body must be scrollable.
    3. Smooth Scrolling: If you use the scrollSmooth option, ensure you do not have scroll-behavior: smooth defined globally in your CSS, as this can cause conflicts.

    To handle fixed headers, pass the header height as headingsOffset and scrollSmoothOffset to prevent the header from covering the heading when scrolling.

    To exclude specific anchor elements from smooth scrolling, add the class no-smooth-scroll to them.

  4. Install and include Tocbot

    master

    You can install Tocbot via npm or include it directly in your HTML using a CDN.

    Using npm

    Install the package:

    npm install --save tocbot

    Then import it using CommonJS or ESM:

    // CommonJS
    const tocbot = require('tocbot/dist/tocbot.js')
    
    // ESM
    import tocbot from 'tocbot'
    
    // Initialize
    tocbot.init()

    Using HTML (CDN)

    Include the script at the bottom of your page before the closing </body> tag:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.32.2/tocbot.min.js"></script>

    Include CSS

    Tocbot requires CSS for styling and handling expanding/collapsing groups.

    Via CDN:

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.32.2/tocbot.css">

    Via Sass/PostCSS (npm):

    @import 'tocbot/src/scss/tocbot';
    npm install --save tocbot
  5. Troubleshoot Tocbot highlighting and scrolling

    master

    Highlighting issues

    If Tocbot scrolls to the right position on click but the active section isn't highlighted, try refreshing with hasInnerContainers: true: tocbot.refresh({ ...tocbot.options, hasInnerContainers: true }).

    Smooth scrolling conflicts

    If you experience strange behavior with scrollSmooth, check if you have scroll-behavior: smooth defined in your global CSS. If so, disable scrollSmooth in your Tocbot configuration.

    Truncated headings

    If you have a very long TOC and headings are being truncated, refer to the known issue #330 for a workaround.

  6. Configure tocbot via IStaticOptions

    master

    The IStaticOptions interface allows you to customize the behavior and appearance of the table of contents. Key configuration areas include:

    Selectors

    • tocSelector: CSS selector where to render the TOC.
    • tocElement: Direct DOM node for the TOC container.
    • contentSelector: CSS selector for the area containing the headings.
    • contentElement: Direct DOM node for the content container.
    • headingSelector: CSS selector for the headings to include (e.g., 'h1, h2, h3').
    • ignoreSelector: CSS selector for headings that should be skipped.

    Styling and Classes

    • linkClass: Main class for TOC links.
    • extraLinkClasses: Additional classes for TOC links.
    • activeLinkClass: Class for the currently active link.
    • listClass: Main class for TOC lists.
    • extraListClasses: Additional classes for TOC lists.
    • isCollapsedClass: Class added when a list is collapsed.
    • collapsibleClass: Class added when a list is capable of being collapsed.
    • listItemClass: Class for list items.
    • activeListItemClass: Class for active list items.

    Behavior and Scrolling

    • collapseDepth: Number of heading levels to keep uncollapsed (e.g., 6 shows all, 0 collapses all).
    • scrollSmooth: Boolean to enable smooth scrolling.
    • scrollSmoothDuration: Duration for smooth scrolling.
    • scrollSmoothOffset: Offset for smooth scrolling.
    • enableUrlHashUpdateOnScroll: Update the URL hash as the user scrolls.
    • scrollHandlerType: Type of scroll handler: 'auto', 'debounce', or 'throttle'.
    • headingsOffset: Minor adjustment for heading position relative to the top.

    Callbacks

    • scrollEndCallback: Triggered when scrolling ends.
    • onClick: Function applied to all TOC links.
    • headingLabelCallback: Modify the text label of a heading.
    • headingObjectCallback: Modify the parsed heading object or exclude it by returning void or nothing.
  7. Configure Tocbot options

    master

    When initializing Tocbot, you can provide an options object to customize the behavior, selectors, and styling of the generated table of contents. Below are the available configuration keys grouped by functionality.

    Selectors and Elements

    • tocSelector: CSS selector where to render the table of contents (e.g., ".js-toc").
    • tocElement: A direct DOM node for the TOC container (overrides tocSelector).
    • contentSelector: CSS selector for the element containing the headings (e.g., ".js-toc-content").
    • contentElement: A direct DOM node for the content container (overrides contentSelector).
    • headingSelector: CSS selector for the headings to grab (e.g., "h1, h2, h3").
    • ignoreSelector: CSS selector for headings that should be skipped.
    • ignoreHiddenElements: Boolean; if true, ignores headings that are hidden in the DOM.

    Styling and Classes

    • linkClass: Main class for TOC links.
    • extraLinkClasses: Additional classes for links.
    • activeLinkClass: Class added to the link corresponding to the top-most heading on the page.
    • listClass: Main class for the TOC lists.
    • extraListClasses: Additional classes for lists.
    • isCollapsedClass: Class added when a list is collapsed.
    • collapsibleClass: Class added when a list is capable of being collapsed.
    • listItemClass: Class for list items.
    • activeListItemClass: Class for active list items.

    Behavior and Scrolling

    • collapseDepth: Number of heading levels that should not be collapsed. 0 collapses everything; a higher number shows more levels.
    • scrollSmooth: Boolean; enables smooth scrolling.
    • scrollSmoothDuration: Duration for smooth scrolling in ms.
    • scrollSmoothOffset: Offset for smooth scrolling.
    • headingsOffset: Minor adjustment for the offset between headings and the top of the document.
    • enableUrlHashUpdateOnScroll: Boolean; updates the URL hash as the user scrolls.
    • scrollHandlerType: Type of scroll handler: "debounce", "throttle", or "auto" (uses debounce if < 333ms, otherwise throttle).
    • scrollHandlerTimeout: Delay for the scroll handler in ms.
    • throttleTimeout: Timeout between events for performance.
    • disableTocScrollSync: Boolean; if true, prevents the TOC scroll position from syncing with the content.
    • tocScrollingWrapper: A DOM node (not a selector) representing an outer element containing the TOC to scroll.
    • tocScrollOffset: Offset for the TOC scroll (top) position.
    • bottomModeThreshold: Threshold for enabling bottom mode to handle links that cannot be scrolled to.

    Callbacks and Customization

    • scrollEndCallback: Function called when scrolling ends. Signature: function(e) { ... }.
    • onClick: Function applied to all links in the TOC. Signature: function(e) { ... }.
    • headingLabelCallback: Function to modify heading labels (e.g., for truncation). Signature: function(string) => string.
    • headingObjectCallback: Function to modify parsed heading properties. Signature: function(object, HTMLElement) => object | void. If nothing is returned, the heading is excluded.

    Advanced and Layout

    • hasInnerContainers: Boolean; set to true for headings inside relative/absolute positioned containers.
    • positionFixedSelector: Selector for the element to receive the positionFixedClass.
    • positionFixedClass: Class to add to make a sidebar fixed after scrolling past fixedSidebarOffset.
    • fixedSidebarOffset: Number or "auto" (defaults to sidebar's offsetTop).
    • includeHtml: Boolean; if true, includes HTML markup from the heading node instead of just innerText.
    • includeTitleTags: Boolean; automatically sets the HTML title attribute of the link to match the heading.
    • orderedList: Boolean; if false, generates <ul> instead of <ol>.
    • scrollContainer: DOM node for a fixed article scroll container to calculate offset.
    • skipRendering: Boolean; prevents rendering if already handled by an external system.
    • basePath: String; useful if using a <base> tag in the <head>.
  8. Troubleshoot Tocbot issues

    master

    Highlighting issues

    If Tocbot scrolls to the right position on click but the active section highlighting is incorrect, try running:

    tocbot.refresh({ ...tocbot.options, hasInnerContainers: true });

    Setting hasInnerContainers: true often resolves issues where headings are inside relative or absolute positioned containers.

    Smooth scrolling conflicts

    If you experience strange behavior after enabling scrollSmooth, check if your CSS has a global scroll-behavior: smooth property. If it does, disable scrollSmooth in your Tocbot configuration.

    Truncated headings

    If you have a very long TOC and headings are being truncated, refer to the community workarounds in the repository issues.

  9. Handle fixed headers with Tocbot

    master

    If your website uses a fixed header, you must pass offsets to tocbot.init so that the scroll position accounts for the header height. For a 40px tall fixed header, use the following configuration:

    tocbot.init({
      headingsOffset: 40,
      scrollSmoothOffset: -40
    })
  10. Refresh tocbot with refresh()

    master
    Use the refresh function to rebuild the table of contents if the document structure has changed (e.g., new headings were added dynamically). You can pass an optional IStaticOptions object to the refresh call.