### Install Tocbot with npm
Source: https://github.com/tscanlin/tocbot/blob/master/README.md
This snippet shows how to install Tocbot using npm, a package manager for Node.js. It is a prerequisite for using Tocbot with module bundlers like Webpack or Rollup, or for importing it into your JavaScript projects.
```bash
npm install --save tocbot
```
--------------------------------
### Customize Tocbot CSS Classes
Source: https://context7.com/tscanlin/tocbot/llms.txt
Provides examples of configuring custom CSS classes for links, lists, and active states, along with corresponding CSS style definitions.
```javascript
tocbot.init({ tocSelector: '.js-toc', contentSelector: '.js-toc-content', headingSelector: 'h1, h2, h3', linkClass: 'toc-link', extraLinkClasses: 'nav-link text-sm', activeLinkClass: 'is-active-link', listClass: 'toc-list', extraListClasses: 'nav-list', listItemClass: 'toc-list-item', activeListItemClass: 'is-active-li', collapsibleClass: 'is-collapsible', isCollapsedClass: 'is-collapsed', collapseDepth: 2, orderedList: false });
```
```css
.toc-link { color: #666; text-decoration: none; } .toc-link.is-active-link { color: #007bff; font-weight: bold; } .toc-list.is-collapsed { display: none; } .toc-list-item.is-active-li > .toc-link { border-left: 2px solid #007bff; }
```
--------------------------------
### Method: tocbot.init
Source: https://github.com/tscanlin/tocbot/blob/master/README.md
Initializes the Tocbot library with a provided configuration object to generate a table of contents.
```APIDOC
## .init
### Description
Initializes the tocbot instance with a set of configuration options.
### Method
JavaScript Function Call
### Parameters
#### Request Body
- **options** (object) - Required - Configuration object containing settings like headingSelector, tocSelector, and contentSelector.
### Request Example
```javascript
tocbot.init({
tocSelector: '.toc',
contentSelector: '.content',
headingSelector: 'h1, h2, h3'
});
```
```
--------------------------------
### Tocbot Initialization Options
Source: https://github.com/tscanlin/tocbot/blob/master/README.md
Illustrates the core usage of Tocbot by initializing it with essential configuration options. These options specify where to render the TOC, where to find the content headings, and which heading levels to include.
```javascript
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,
});
```
--------------------------------
### Tocbot Initialization API
Source: https://github.com/tscanlin/tocbot/blob/master/README.md
This section details how to initialize Tocbot with various configuration options, including selectors for TOC rendering and content, heading selection, and handling inner containers.
```APIDOC
## Tocbot Initialization API
### Description
Initializes Tocbot to generate a table of contents based on specified configuration options.
### Method
`tocbot.init(options)`
### Parameters
#### Request Body (Options Object)
- **tocSelector** (string) - Required - CSS selector for the element where the table of contents will be rendered.
- **contentSelector** (string) - Required - CSS selector for the element containing the headings to build the table of contents from.
- **headingSelector** (string) - Optional - CSS selector for the headings to grab within the `contentSelector`. Defaults to 'h1, h2, h3'.
- **hasInnerContainers** (boolean) - Optional - Set to true if headings are inside relative or absolute positioned containers within `contentSelector`. Defaults to false.
- **headingsOffset** (number) - Optional - Offset in pixels to adjust for fixed headers when scrolling to headings.
- **scrollSmoothOffset** (number) - Optional - Offset in pixels for smooth scrolling, typically used to counteract `headingsOffset` for fixed headers.
### Request Example
```javascript
tocbot.init({
tocSelector: '.js-toc',
contentSelector: '.js-toc-content',
headingSelector: 'h1, h2, h3',
hasInnerContainers: true,
headingsOffset: 40,
scrollSmoothOffset: -40
});
```
### Response
#### Success Response (200)
Tocbot initializes and renders the table of contents. No explicit return value is documented for `init`.
#### Response Example
(No specific response body is returned; the effect is the rendering of the TOC.)
```
--------------------------------
### Initialize Tocbot with Selectors and Elements
Source: https://context7.com/tscanlin/tocbot/llms.txt
Shows how to target specific DOM elements or use CSS selectors to define the TOC container and the content area to be scanned.
```javascript
tocbot.init({ tocSelector: '.js-toc', contentSelector: '.js-toc-content', headingSelector: 'h1, h2, h3, h4', ignoreSelector: '.js-toc-ignore' }); const tocElement = document.getElementById('table-of-contents'); const contentElement = document.querySelector('article.main-content'); tocbot.init({ tocElement: tocElement, contentElement: contentElement, headingSelector: 'h2, h3, h4', ignoreSelector: '.toc-skip, .no-toc' });
```
--------------------------------
### Tocbot Usage with TypeScript
Source: https://context7.com/tscanlin/tocbot/llms.txt
Demonstrates how to use Tocbot in a TypeScript project with type-safe configuration options. It covers initialization, refreshing the TOC with partial options, and destroying the Tocbot instance.
```typescript
import * as tocbot from 'tocbot';
// Full typed configuration
const options: tocbot.IStaticOptions = {
tocSelector: '.js-toc',
contentSelector: '.js-toc-content',
headingSelector: 'h1, h2, h3',
collapseDepth: 3,
scrollSmooth: true,
scrollSmoothDuration: 420,
scrollSmoothOffset: -60,
headingsOffset: 60,
activeLinkClass: 'is-active-link',
listClass: 'toc-list',
linkClass: 'toc-link',
orderedList: true,
onClick: (e: MouseEvent) => {
console.log('Link clicked');
},
scrollEndCallback: (e: WheelEvent) => {
console.log('Scroll ended');
},
headingLabelCallback: (label: string): string => {
return label.length > 50 ? `${label.slice(0, 50)}...` : label;
},
headingObjectCallback: (obj: object, node: HTMLElement): object | void => {
if (node.classList.contains('hidden')) {
return; // Exclude from TOC
}
return obj;
},
};
// Initialize
tocbot.init(options);
// Refresh with partial options
tocbot.refresh({
headingSelector: 'h1, h2, h3, h4',
});
// Cleanup
tocbot.destroy();
```
--------------------------------
### Import Tocbot in JavaScript (ESM/CommonJS)
Source: https://context7.com/tscanlin/tocbot/llms.txt
Demonstrates how to import Tocbot using both ECMAScript Modules (ESM) and CommonJS module systems.
```javascript
// ESM import
import tocbot from 'tocbot'
// CommonJS require
const tocbot = require('tocbot/dist/tocbot.js')
```
--------------------------------
### Initialize Tocbot with JavaScript
Source: https://github.com/tscanlin/tocbot/blob/master/README.md
Demonstrates how to initialize Tocbot in a JavaScript project. It covers both CommonJS and ESM import methods. Tocbot requires initialization with specific selectors for the TOC container and the content containing the headings.
```javascript
const tocbot = require('tocbot/dist/tocbot.js')
// OR
import tocbot from 'tocbot'
// Initialize tocbot
tocbot.init()
```
```javascript
import * as tocbot from 'tocbot';
tocbot.init({
// Options
});
tocbot.refresh();
tocbot.destroy();
```
--------------------------------
### Run Tocbot Tests
Source: https://github.com/tscanlin/tocbot/blob/master/README.md
Command to execute the test suite for the project using the npm package manager.
```bash
npm run test
```
--------------------------------
### Configuration Options - Selectors and Elements
Source: https://context7.com/tscanlin/tocbot/llms.txt
Details on how to configure Tocbot using CSS selectors or DOM elements for TOC and content areas.
```APIDOC
## Configuration Options - Selectors and Elements
### Description
Configure where tocbot renders the TOC and which content it scans for headings. You can use CSS selectors or pass DOM elements directly for more control.
### Parameters
- **tocSelector** (string | HTMLElement) - CSS selector or DOM element where the TOC will be rendered.
- **contentSelector** (string | HTMLElement) - CSS selector or DOM element containing the headings to be included in the TOC.
- **headingSelector** (string) - CSS selector to identify headings within the content area (e.g., 'h1, h2, h3').
- **ignoreSelector** (string) - CSS selector to exclude specific headings from the TOC (e.g., '.js-toc-ignore', '.toc-skip').
### Request Example
```javascript
// Using CSS selectors (default approach)
tocbot.init({
tocSelector: '.js-toc',
contentSelector: '.js-toc-content',
headingSelector: 'h1, h2, h3, h4',
ignoreSelector: '.js-toc-ignore' // Skip these headings
});
// Using DOM elements directly
const tocElement = document.getElementById('table-of-contents');
const contentElement = document.querySelector('article.main-content');
tocbot.init({
tocElement: tocElement,
contentElement: contentElement,
headingSelector: 'h2, h3, h4',
ignoreSelector: '.toc-skip, .no-toc'
});
```
### Example HTML with ignored heading
```html
This Won't Appear in TOC
Neither Will This
This Will Appear
```
```
--------------------------------
### Configuration Options - Scrolling and Positioning
Source: https://context7.com/tscanlin/tocbot/llms.txt
Options for controlling smooth scrolling, fixed sidebar behavior, and scroll offsets.
```APIDOC
## Configuration Options - Scrolling and Positioning
### Description
Control smooth scrolling behavior, fixed sidebar positioning, and scroll offsets for fixed headers. These options ensure the TOC works correctly with various page layouts.
### Parameters
- **scrollSmooth** (boolean) - Enable or disable smooth scrolling animation when clicking TOC links.
- **scrollSmoothDuration** (number) - The duration in milliseconds for the smooth scrolling animation.
- **scrollSmoothOffset** (number) - An offset in pixels to adjust the scroll target. Useful for accounting for fixed headers (use a negative value).
- **scrollEndCallback** (function) - A callback function that is executed once the scroll animation completes.
- **headingsOffset** (number) - An offset in pixels used to calculate the active heading. Should generally match the height of a fixed header.
- **positionFixedSelector** (string) - CSS selector for an element that should become fixed (stick) to the viewport when scrolling past a certain point.
- **positionFixedClass** (string) - The CSS class to add to the element specified by `positionFixedSelector` when it becomes fixed.
- **fixedSidebarOffset** (number | 'auto') - The offset from the top of the viewport when the sidebar should become fixed. 'auto' attempts to calculate it.
- **scrollContainer** (string | HTMLElement) - Selector or DOM element for a custom scrollable container if the main page scrollbar is not used.
- **scrollHandlerType** (string) - Specifies the optimization strategy for the scroll event handler ('debounce', 'throttle', or 'auto').
- **scrollHandlerTimeout** (number) - Timeout in milliseconds for the scroll handler (used with 'debounce' or 'throttle').
- **throttleTimeout** (number) - Specific timeout for 'throttle' optimization.
### Request Example
```javascript
// Basic scrolling and positioning setup
tocbot.init({
tocSelector: '.js-toc',
contentSelector: '.js-toc-content',
headingSelector: 'h1, h2, h3',
// Smooth scrolling
scrollSmooth: true,
scrollSmoothDuration: 420,
scrollSmoothOffset: -60, // Offset for a 60px fixed header
scrollEndCallback: function(e) {
console.log('Scroll animation completed');
},
// Heading offset for highlighting calculation
headingsOffset: 60, // Matches fixed header height
// Fixed sidebar positioning
positionFixedSelector: '.js-toc-wrapper',
positionFixedClass: 'is-position-fixed',
fixedSidebarOffset: 100,
// Custom scroll container (for scrollable divs)
scrollContainer: '.scrollable-content',
// Scroll handler optimization
scrollHandlerType: 'auto',
scrollHandlerTimeout: 50,
throttleTimeout: 50,
});
// Example: Fixed 60px header setup
tocbot.init({
tocSelector: '.js-toc',
contentSelector: '.js-toc-content',
headingSelector: 'h1, h2, h3',
headingsOffset: 60,
scrollSmoothOffset: -60
});
```
```
--------------------------------
### Initialize and Manage Tocbot
Source: https://github.com/tscanlin/tocbot/blob/master/README.md
Methods for controlling the lifecycle of the Tocbot instance, including initialization with options, manual destruction, and refreshing the table of contents.
```javascript
tocbot.init(options);
tocbot.destroy();
tocbot.refresh();
```
--------------------------------
### Initialize Tocbot with Options
Source: https://context7.com/tscanlin/tocbot/llms.txt
Initializes Tocbot to generate a table of contents. It requires selectors for the TOC container and the content area containing headings. Options control behavior like heading levels, smooth scrolling, and collapse depth.
```html
Introduction
Welcome to the documentation...
Getting Started
First, install the package...
Installation
Run npm install...
Configuration
Configure with options...
API Reference
The following methods are available...
init()
Initialize tocbot...
destroy()
Cleanup tocbot...
```
--------------------------------
### Include Tocbot CSS
Source: https://github.com/tscanlin/tocbot/blob/master/README.md
Provides instructions for including Tocbot's CSS for styling and functionality, such as expanding and collapsing groups. It shows both CDN and Sass import methods.
```html
```
```scss
@import 'tocbot/src/scss/tocbot';
```
--------------------------------
### Initialize Tocbot Configuration
Source: https://github.com/tscanlin/tocbot/blob/master/README.md
This object defines the configuration parameters for the Tocbot library. It allows developers to specify target selectors, customize CSS classes for styling, and control scroll behavior and event callbacks.
```javascript
tocbot.init({
tocSelector: '.js-toc',
contentSelector: '.js-toc-content',
headingSelector: 'h1, h2, h3',
ignoreSelector: '.js-toc-ignore',
hasInnerContainers: false,
linkClass: 'toc-link',
activeLinkClass: 'is-active-link',
listClass: 'toc-list',
isCollapsedClass: 'is-collapsed',
collapsibleClass: 'is-collapsible',
listItemClass: 'toc-list-item',
activeListItemClass: 'is-active-li',
collapseDepth: 0,
scrollSmooth: true,
scrollSmoothDuration: 420,
scrollSmoothOffset: 0,
headingsOffset: 1,
enableUrlHashUpdateOnScroll: false,
scrollHandlerType: 'auto',
scrollHandlerTimeout: 50,
throttleTimeout: 50,
positionFixedClass: 'is-position-fixed',
fixedSidebarOffset: 'auto',
includeHtml: false,
includeTitleTags: false,
orderedList: true,
skipRendering: false,
ignoreHiddenElements: false,
onClick: function (e) {},
scrollEndCallback: function (e) {},
headingLabelCallback: false
});
```
--------------------------------
### Tocbot Initialization with Skip Rendering (JavaScript)
Source: https://context7.com/tscanlin/tocbot/llms.txt
Initializes Tocbot to handle scroll highlighting and smooth scrolling features without rendering the TOC itself, useful when an external system manages TOC generation. It requires the TOC HTML to be manually inserted into the DOM.
```javascript
// External system renders TOC HTML
const tocHtml = `
`;
document.getElementById('toc-container').innerHTML = tocHtml;
// Initialize tocbot for scroll behavior only
tocbot.init({
tocSelector: '#custom-toc',
contentSelector: '.content',
headingSelector: 'h1, h2, h3',
skipRendering: true, // Don't render TOC, just handle scroll events
scrollSmooth: true,
scrollSmoothDuration: 300,
});
```
--------------------------------
### Refresh Tocbot for Dynamic Content
Source: https://context7.com/tscanlin/tocbot/llms.txt
Demonstrates how to reinitialize the table of contents after dynamic content updates or to apply new configuration options.
```javascript
tocbot.init({ tocSelector: '.js-toc', contentSelector: '.js-toc-content', headingSelector: 'h1, h2, h3' }); async function loadNewSection() { const response = await fetch('/api/section/advanced'); const html = await response.text(); document.querySelector('.js-toc-content').innerHTML += html; tocbot.refresh(); } function expandTocDepth() { tocbot.refresh({ tocSelector: '.js-toc', contentSelector: '.js-toc-content', headingSelector: 'h1, h2, h3, h4', collapseDepth: 4 }); } function fixHighlighting() { tocbot.refresh({ ...tocbot.options, hasInnerContainers: true }); }
```
--------------------------------
### Tocbot Initialization with URL Hash and Advanced Features (JavaScript)
Source: https://context7.com/tscanlin/tocbot/llms.txt
Initializes Tocbot with options to update the URL hash on scroll, include HTML in TOC links, use title tags, and apply custom callbacks for heading labels and objects. It also configures click handlers and ignores hidden elements.
```javascript
tocbot.init({
tocSelector: '.js-toc',
contentSelector: '.js-toc-content',
headingSelector: 'h1, h2, h3',
// Update URL hash as user scrolls
enableUrlHashUpdateOnScroll: true,
// Include HTML markup from headings (icons, etc.)
includeHtml: true,
// Add title attributes to links (useful for truncated titles)
includeTitleTags: true,
// Custom heading label transformation
headingLabelCallback: function(headingText) {
// Truncate long headings with ellipsis
if (headingText.length > 30) {
return headingText.substring(0, 30) + '...';
}
return headingText;
},
// Advanced heading processing
headingObjectCallback: function(obj, heading) {
// Add custom data or modify heading object
obj.customData = heading.dataset.category;
// Return null to exclude heading from TOC
if (heading.classList.contains('draft')) {
return null;
}
return obj;
},
// Click handler for TOC links
onClick: function(e) {
console.log('TOC link clicked:', e.target.href);
// Can prevent default, stop propagation, or track analytics
},
// Ignore hidden elements in DOM
ignoreHiddenElements: true,
// Base path for links (useful with tag)
basePath: '/docs',
// TOC scroll sync options
disableTocScrollSync: false,
tocScrollOffset: 30,
});
// Using data-heading-label for custom TOC text
//
Application Programming Interface Reference
// TOC will show "API" instead of the full heading text
```
--------------------------------
### Configure Fixed Headers with Tocbot
Source: https://github.com/tscanlin/tocbot/blob/master/README.md
Explains how to adjust Tocbot's behavior to accommodate fixed headers on a page. By providing `headingsOffset` and `scrollSmoothOffset`, the script ensures correct scrolling and anchor linking even with a sticky header.
```javascript
tocbot.init({
headingsOffset: 40,
scrollSmoothOffset: -40
})
```
--------------------------------
### Refresh Tocbot Instance
Source: https://github.com/tscanlin/tocbot/blob/master/README.md
Demonstrates how to refresh an existing Tocbot instance, which is useful when the content of the page changes dynamically. This allows the TOC to be updated without reinitializing the entire script.
```javascript
tocbot.refresh();
```
--------------------------------
### Include Tocbot via HTML script tag
Source: https://github.com/tscanlin/tocbot/blob/master/README.md
This shows how to include the Tocbot library directly in an HTML file using a script tag. This method is suitable for projects that do not use a module bundler and prefer to include scripts directly.
```html
```
--------------------------------
### Generate Heading IDs with makeIds Utility
Source: https://context7.com/tscanlin/tocbot/llms.txt
The makeIds utility automatically assigns unique ID attributes to headings that lack them, which is required for Tocbot hash links to function. It can be used via a script include or implemented manually in JavaScript to scan content and apply IDs based on heading text.
```html
```
```javascript
function makeIds() {
const content = document.querySelector('.js-toc-content');
const headings = content.querySelectorAll('h1, h2, h3, h4, h5, h6');
const headingMap = {};
headings.forEach(function(heading) {
const id = heading.id
? heading.id
: heading.innerText
.trim()
.toLowerCase()
.replace(/\s+/g, '-')
.replace(/[^a-z0-9-]/g, '');
headingMap[id] = !isNaN(headingMap[id]) ? ++headingMap[id] : 0;
if (headingMap[id]) {
heading.id = id + '-' + headingMap[id];
} else {
heading.id = id;
}
});
}
```
--------------------------------
### Configuration Options - CSS Classes
Source: https://context7.com/tscanlin/tocbot/llms.txt
Customize the CSS classes applied to TOC elements for styling control.
```APIDOC
## Configuration Options - CSS Classes
### Description
Customize the CSS classes applied to TOC elements for full styling control. Each element type can have custom classes for both normal and active states.
### Parameters
- **linkClass** (string) - Base CSS class for all TOC links.
- **extraLinkClasses** (string) - Additional CSS classes to apply to TOC links.
- **activeLinkClass** (string) - CSS class applied to the currently active TOC link.
- **listClass** (string) - Base CSS class for TOC lists (
or ).
- **extraListClasses** (string) - Additional CSS classes to apply to TOC lists.
- **listItemClass** (string) - CSS class for individual list items (
).
- **activeListItemClass** (string) - CSS class applied to the active list item.
- **collapsibleClass** (string) - CSS class applied to sections that are collapsible.
- **isCollapsedClass** (string) - CSS class applied to sections that are currently collapsed.
- **collapseDepth** (number) - The nesting depth at which sections should initially be collapsed.
- **orderedList** (boolean) - If true, uses ``; otherwise, uses `
`.
### Request Example
```javascript
tocbot.init({
tocSelector: '.js-toc',
contentSelector: '.js-toc-content',
headingSelector: 'h1, h2, h3',
// Link styling
linkClass: 'toc-link',
extraLinkClasses: 'nav-link text-sm',
activeLinkClass: 'is-active-link',
// List styling
listClass: 'toc-list',
extraListClasses: 'nav-list',
listItemClass: 'toc-list-item',
activeListItemClass: 'is-active-li',
// Collapse behavior
collapsibleClass: 'is-collapsible',
isCollapsedClass: 'is-collapsed',
collapseDepth: 2,
// Use unordered lists instead of ordered
orderedList: false,
});
```
### Corresponding CSS Example
```css
.toc-link {
color: #666;
text-decoration: none;
}
.toc-link.is-active-link {
color: #007bff;
font-weight: bold;
}
.toc-list.is-collapsed {
display: none;
}
.toc-list-item.is-active-li > .toc-link {
border-left: 2px solid #007bff;
}
```
```
--------------------------------
### Configure Scrolling and Positioning
Source: https://context7.com/tscanlin/tocbot/llms.txt
Configures smooth scrolling, fixed sidebar behavior, and scroll offsets to ensure the TOC interacts correctly with fixed headers and scrollable containers.
```javascript
tocbot.init({ tocSelector: '.js-toc', contentSelector: '.js-toc-content', headingSelector: 'h1, h2, h3', scrollSmooth: true, scrollSmoothDuration: 420, scrollSmoothOffset: -60, scrollEndCallback: function(e) { console.log('Scroll animation completed'); }, headingsOffset: 60, positionFixedSelector: '.js-toc-wrapper', positionFixedClass: 'is-position-fixed', fixedSidebarOffset: 100, scrollContainer: '.scrollable-content', scrollHandlerType: 'auto', scrollHandlerTimeout: 50, throttleTimeout: 50 });
```
--------------------------------
### Include Tocbot via CDN
Source: https://context7.com/tscanlin/tocbot/llms.txt
Includes Tocbot and its CSS directly from a CDN. This method is suitable for quick integration or projects not using a package manager.
```html
```
--------------------------------
### Method: tocbot.refresh
Source: https://github.com/tscanlin/tocbot/blob/master/README.md
Refreshes the Tocbot instance, useful when the document content has changed dynamically.
```APIDOC
## .refresh
### Description
Rebuilds the table of contents based on the current state of the document. Useful if headings are added or removed after initial load.
### Method
JavaScript Function Call
### Request Example
```javascript
tocbot.refresh();
```
```
--------------------------------
### Customize Tocbot with SCSS
Source: https://context7.com/tscanlin/tocbot/llms.txt
Import Tocbot's core styles and default themes into your build pipeline. You can override Sass variables or apply custom CSS rules to style the table of contents list and active link states.
```scss
@import 'tocbot/src/scss/tocbot';
.toc-link {
display: block;
padding: 0.25rem 0.5rem;
color: #495057;
text-decoration: none;
border-left: 2px solid transparent;
transition: all 0.2s ease;
&.is-active-link {
color: #007bff;
border-left-color: #007bff;
font-weight: 600;
}
}
```
--------------------------------
### tocbot.refresh(options)
Source: https://context7.com/tscanlin/tocbot/llms.txt
Rebuilds the table of contents, useful for dynamically changing document content. It destroys the existing TOC and reinitializes with new or previous options.
```APIDOC
## tocbot.refresh(options)
### Description
Rebuilds the table of contents when the document content changes dynamically. This destroys the existing TOC and reinitializes with the provided options (or the previously used options if none specified). Use this after adding, removing, or modifying headings in the content area.
### Method
`tocbot.refresh()`
### Parameters
#### Options Object (Optional)
- **tocSelector** (string) - Selector for the TOC container.
- **contentSelector** (string) - Selector for the content area containing headings.
- **headingSelector** (string) - CSS selector for headings to include.
- **ignoreSelector** (string) - CSS selector for headings to ignore.
- **hasInnerContainers** (boolean) - Set to true to fix highlighting issues with inner containers.
- **collapseDepth** (number) - The depth at which to start collapsing sections.
### Request Example
```javascript
// Refresh with default options
tocbot.refresh();
// Refresh with new options to include h4 headings
tocbot.refresh({
headingSelector: 'h1, h2, h3, h4',
collapseDepth: 4
});
// Fix highlighting issues with inner containers
tocbot.refresh({ ...tocbot.options, hasInnerContainers: true });
```
### Response
This method does not return a value, but modifies the DOM to update the TOC.
```
--------------------------------
### Tocbot Refresh API
Source: https://github.com/tscanlin/tocbot/blob/master/README.md
Details on how to refresh the table of contents if the content has changed dynamically.
```APIDOC
## Tocbot Refresh API
### Description
Refreshes the table of contents to reflect any changes in the content headings. This can optionally be called with new options to update the configuration.
### Method
`tocbot.refresh(options)`
### Parameters
#### Request Body (Options Object - Optional)
- **tocSelector** (string) - Optional - New CSS selector for the TOC container.
- **contentSelector** (string) - Optional - New CSS selector for the content area.
- **headingSelector** (string) - Optional - New CSS selector for headings.
- **hasInnerContainers** (boolean) - Optional - New value for `hasInnerContainers`.
- **headingsOffset** (number) - Optional - New value for `headingsOffset`.
- **scrollSmoothOffset** (number) - Optional - New value for `scrollSmoothOffset`.
### Request Example
```javascript
// Refresh with existing options
tocbot.refresh();
// Refresh with new options
tocbot.refresh({
tocSelector: '.new-toc-container',
headingSelector: 'h2, h3'
});
```
### Response
#### Success Response (200)
Tocbot updates the table of contents based on the current or provided options. No explicit return value is documented for `refresh`.
#### Response Example
(No specific response body is returned; the effect is the update of the TOC.)
```
--------------------------------
### Tocbot Destroy API
Source: https://github.com/tscanlin/tocbot/blob/master/README.md
Information on how to remove the table of contents generated by Tocbot.
```APIDOC
## Tocbot Destroy API
### Description
Removes the table of contents generated by Tocbot from the DOM and cleans up any associated event listeners.
### Method
`tocbot.destroy()`
### Parameters
None.
### Request Example
```javascript
tocbot.destroy();
```
### Response
#### Success Response (200)
The table of contents is removed from the DOM. No explicit return value is documented for `destroy`.
#### Response Example
(No specific response body is returned; the effect is the removal of the TOC.)
```
--------------------------------
### Method: tocbot.destroy
Source: https://github.com/tscanlin/tocbot/blob/master/README.md
Destroys the current Tocbot instance and removes all associated event listeners.
```APIDOC
## .destroy
### Description
Cleans up the tocbot instance, removing event listeners and clearing the DOM elements managed by the library.
### Method
JavaScript Function Call
### Request Example
```javascript
tocbot.destroy();
```
```
--------------------------------
### Destroy Tocbot Instance
Source: https://context7.com/tscanlin/tocbot/llms.txt
Removes the generated table of contents and cleans up all associated event listeners. This is crucial for single-page applications to prevent memory leaks when reinitializing or navigating away.
```javascript
// Initialize tocbot on page load
tocbot.init({
tocSelector: '.js-toc',
contentSelector: '.js-toc-content',
headingSelector: 'h1, h2, h3',
});
// Cleanup when navigating away (e.g., in a SPA)
function cleanup() {
tocbot.destroy();
// TOC HTML is cleared and all scroll/click listeners are removed
}
// Example: React useEffect cleanup
// useEffect(() => {
// tocbot.init({ ... });
// return () => tocbot.destroy();
// }, []);
// Example: Vue beforeUnmount
// beforeUnmount() {
// tocbot.destroy();
// }
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.