sv-toc logo sv-toc

Readme | Demo | Docs


sv-toc

NPM Downloads GitHub License GitHub Repo stars NPM Version

sv-toc is a simple Svelte library for reactive tables of contents, including scroll tracking, automatic heading detection and updates, and (if you want) ID generation for headings.

Features

  • Automatic heading detection
  • Customizable heading selector (even non non-<h*> elements should work)
  • Customizable selector for where to search for headings

Optional Features

  • DOM watching for heading changes
  • Scroll tracking to mark headings as active
    • Customizable selector for a scroll container instead of window
    • Ability to specify top/bottom offsets
    • Three modes: first and last highlight only one heading as active at a time, while all highlights all sections that are currently in view
  • ID generation for headings

Installation

npm install sv-toc
yarn add sv-toc
pnpm add sv-toc
bun add sv-toc

Usage

<script lang="ts">
  import { class TocToc } from "sv-toc";

  const const toc: Toctoc = new new Toc(config?: TocConfig): TocToc({
    headingSelector?: string | undefined
CSS selector used to identify heading elements within the document. A common use case may be to only observe headings starting at a specific level, such as "h2, h3, h4".
@default"h1, h2, h3, h4, h5, h6"
headingSelector
: "h2, h3, h4, h5, h6",
}); </script> <!-- Now do whatever you want with toc.current --> {#each const toc: Toctoc.Toc.current: TocHeading[]
The current table of content
current
as let heading: TocHeadingheading, let index: numberindex (let index: numberindex)}
... {/each}

Documentation

You can find the full documentation here.