scrollbar-toc

A scrollbar-style fixed table of contents component for all JavaScript web frameworks and libraries. Automatically parse headings (h1~h6) in documents and create intuitive navigation buttons positioned proportionally to viewport height in the browser scrollbar area.

🚀
Zero Dependencies
No peer dependencies required. Works with pure DOM APIs for maximum compatibility.
🎯
Framework Agnostic
Works with React, Vue, Svelte, or vanilla JavaScript. Universal compatibility.

Installation

npm install scrollbar-toc

Quick Start

The simplest way to add a table of contents to your document:

Basic Usage

import { setScrollToc } from 'scrollbar-toc'

const article = document.querySelector('article')
setScrollToc(article)

setScrollToc(article, {
    className: 'custom-toc',
    rightOffset: 20,
    scrollOffset: -80,
    exceptLevel: [1, 2],
    onClick: (position) => {
        console.log('Navigated to:', position.element.textContent)
    }
})

Framework Integration

React

Integration with React using useEffect and useRef:

React Integration
import { useEffect, useRef } from 'react'
import { setScrollToc } from 'scrollbar-toc'

export const Article = () => {
    const contentRef = useRef<HTMLDivElement>(null)

    useEffect(() => {
        if (contentRef.current) {
            setScrollToc(contentRef.current, {
                className: 'article-toc',
                scrollOffset: -64,
                onClick: (pos) => {
                    analytics.track('toc_clicked', {
                        heading: pos.element.textContent
                    })
                }
            })
        }
    }, [])

    return <div ref={contentRef}>{/* Content */}</div>
}

Key Features

Automatic Heading Detection

The library automatically detects all heading elements (h1-h6) in your document and creates navigation buttons positioned proportionally to the document height.

Smart Positioning with Overlap Prevention

Buttons are positioned using a sophisticated algorithm that maps document scroll positions to viewport coordinates. When buttons are too close together, they are automatically grouped and repositioned to prevent overlap, ensuring clear navigation with a minimum gap based on button height (default: 16px).

Extensive Customization

Customize appearance with CSS classes, adjust positioning with offsets, and add custom click handlers for analytics or other functionality.

Selective Heading Levels

Choose which heading levels to include in the TOC using the exceptLevel option. For example, exceptLevel: [1] excludes h1 elements, exceptLevel: [1, 2] excludes both h1 and h2 elements.

Browser Support

✅ Chrome 60+✅ Firefox 60+✅ Safari 12+✅ Edge 79+

Bundle Size

Lightweight and optimized for production:

ESM: ~2KBCJS: ~2.2KBTree-shakeable