Security News
JSR Working Group Kicks Off with Ambitious Roadmap and Plans for Open Governance
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
Generate a table of contents based on the heading structure of a html document.
The tocbot npm package is designed to generate a table of contents (TOC) based on the headings in a given HTML document. It automatically creates a TOC that can be styled and configured to enhance navigation within long documents, making it easier for users to jump to different sections.
Generate TOC
This feature allows you to generate a table of contents by specifying the selectors for the TOC container, the content where the headings are located, and the headings to be included in the TOC.
tocbot.init({
tocSelector: '.js-toc',
contentSelector: '.js-toc-content',
headingSelector: 'h1, h2, h3'
});
Customize TOC Styling
This feature allows you to customize the classes applied to the TOC links, active links, list, and list items, enabling you to style the TOC to match your site's design.
tocbot.init({
tocSelector: '.js-toc',
contentSelector: '.js-toc-content',
headingSelector: 'h1, h2, h3',
linkClass: 'toc-link',
activeLinkClass: 'is-active-link',
listClass: 'toc-list',
listItemClass: 'toc-list-item'
});
Smooth Scrolling
This feature enables smooth scrolling when a user clicks on a TOC link, providing a better user experience.
tocbot.init({
tocSelector: '.js-toc',
contentSelector: '.js-toc-content',
headingSelector: 'h1, h2, h3',
scrollSmooth: true
});
Collapse Sub-Headings
This feature allows you to specify the depth of headings that should be collapsible, helping to keep the TOC concise and focused on higher-level headings.
tocbot.init({
tocSelector: '.js-toc',
contentSelector: '.js-toc-content',
headingSelector: 'h1, h2, h3',
collapseDepth: 3
});
The markdown-toc package generates a TOC for markdown files. Unlike tocbot, which operates on HTML content in the browser, markdown-toc is used primarily in Node.js environments or as part of a build process for markdown files.
Doctoc is another tool for generating a TOC for markdown files, which can be used in a command-line environment. It is similar to markdown-toc but also supports updating existing TOCs within a document.
The toc package is a Node.js module that generates a JSON representation of a TOC for HTML content. It differs from tocbot in that it does not provide the functionality to automatically insert the TOC into a webpage.
Tocbot builds a table of contents (TOC) from headings in an HTML document. This is useful for documentation websites or long markdown pages because it makes them easier to navigate. This library was inspired by Tocify, the main difference is that Tocbot uses native DOM methods and avoids the jQuery & jQuery UI dependencies.
You can use npm to install it or include the script on the page with HTML.
Install it with npm.
npm install --save tocbot
Then use with either commonjs or ESM imports:
const tocbot = require('tocbot/dist/tocbot.js')
// OR
import tocbot from 'tocbot'
// Initialize tocbot
tocbot.init()
OR
Include the script at the bottom of the page before the closing body tag.
<script src="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.27.4/tocbot.min.js"></script>
CSS is used for expanding & collapsing groupings and some basic styling.
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.27.4/tocbot.css">
OR
If you installed it with npm and use sass / postcss you might try importing the styles from 'node_modules', see the includePath option documentation for more info
@import 'tocbot/src/scss/tocbot';
Initialize the script at the bottom of the page before the closing body tag.
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,
});
NOTE: Make sure the body is scrollable and the document headings have id attributes, tocbot and your browser needs these things to make hashes jump to the proper heading, some markdown libraries (like marked) already do this for you.
If content in the div has changed then trigger a refresh (optionally with new options).
tocbot.refresh();
Also you can use it within typescript:
import * as tocbot from 'tocbot';
tocbot.init({
// Options
});
tocbot.refresh();
tocbot.destroy();
If you'd like to add your page to this list open a pull request.
This library uses vanilla JavaScript. It is less than 350 bytes of CSS and about 3.6Kb of JavaScript (minified and gzipped) it also has no dependencies.
This script works in all modern browsers and IE 9+.
Make sure rendered headings have id attributes, some markdown libraries (like marked) already do this. If you need to do this client side see this script.
NOTE: to exclude anchor elements from smooth scrolling, add the class no-smooth-scroll
.
To handle fixed headers with tocbot, just pass the header offsets as options to tocbot. For example, the options needed for a 40px
tall fixed header would be:
tocbot.init({
headingsOffset: 40,
scrollSmoothOffset: -40
})
// Where to render the table of contents.
tocSelector: '.js-toc',
// Or, you can pass in a DOM node instead
tocElement: element,
// Where to grab the headings to build the table of contents.
contentSelector: '.js-toc-content',
// Or, you can pass in a DOM node instead
contentElement: element,
// 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 collapsed.
collapsibleClass: 'is-collapsible',
// Class to add to list items.
listItemClass: 'toc-list-item',
// Class to add to active list items.
activeListItemClass: 'is-active-li',
// How many heading levels should not be collapsed.
// For example, number 6 will show everything since
// there are only 6 heading levels and number 0 will collapse 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,
// Smooth scroll offset.
scrollSmoothOffset: 0,
// 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 innerText.
includeHtml: false,
// includeTitleTags automatically sets the html title tag of the link
// to match the title. This can be useful for SEO purposes or
// when truncating titles.
includeTitleTags: false,
// 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: function (e) {},
// 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 and returns the modified label to display.
// Additionally, the attribute `data-heading-label` may be used on a heading to specify
// a shorter string to be used in the TOC.
// 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,
// 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,
// Offset for the toc scroll (top) position when scrolling the page.
// Only effective if `disableTocScrollSync` is false.
tocScrollOffset: 0,
Initialize tocbot with an options object.
tocbot.init(options)
Destroy tocbot and remove event listeners.
tocbot.destroy()
Refresh tocbot if the document changes and it needs to be rebuilt.
tocbot.refresh()
tocbot.refresh({ ...tocbot.options, hasInnerContainers: true })
. If that works then one option (hasInnerContainers: true
) to handle inner containers should be all you need to add.Contributions and suggestions are welcome! Please feel free to open an issue if you run into a problem or have a feature request. I'll do my best to respond in a timely fashion.
If you want to open a pull request just fork the repo but please make sure all tests and lint pass.
npm run test
npm version <patch|minor|major>
npm publish
FAQs
Generate a table of contents based on the heading structure of a html document.
The npm package tocbot receives a total of 1,833,449 weekly downloads. As such, tocbot popularity was classified as popular.
We found that tocbot demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
Security News
Research
An advanced npm supply chain attack is leveraging Ethereum smart contracts for decentralized, persistent malware control, evading traditional defenses.
Security News
Research
Attackers are impersonating Sindre Sorhus on npm with a fake 'chalk-node' package containing a malicious backdoor to compromise developers' projects.