Table of Contents

Svelte Component

Allows you to quickly navigate the hierarchy of headings for the current page.

Examples

Getting Started

Add the component to a page, set the target property, then a list of links will be auto-generated based on available HTML headings.

html
<TableOfContents target="#toc-target" />
html
<!-- NOTE: this can be the body element, App Shell #page, etc. -->
<main>
	<!-- The region to scan for heading elements. -->
	<div id="toc-target">
		<h2>Heading<h2>
		<p>Lorem, ipsum dolor sit amet consectetur adipisicing elit.</p>
		<h3>Subheading<h3>
		<p>Lorem, ipsum dolor sit amet consectetur adipisicing elit.</p>
	</div>
</main>

How It Works

Key Props

The following props are critical to how this operates.

Property Example Description
scrollParent "#page" Query selector for the scrollable page element.
target "#page" Query selector for the element to scan for headings.
allowedHeadings 'h2, h3' Query selector for the allowed headings. From H2-H6.

Heading IDs

The component will scan the target region and query all matching headings. If a heading has an ID set, that will be used as the scroll target, otherwise an ID will be auto-generated and assigned.

Click to Scroll

When a link is clicked, the scrollable parent container will be scrolled using the JavaScript scrollIntoView method. This will smoothly scroll the container element to the heading with the matching ID.

Ignore a Heading

By default, the Table of Contents creates links for all headings within the target region. If you wish to ignore certain headings, add the following data attribute to that heading.

html
<h2 data-toc-ignore>Ignore Me!</h2>

Screen Reader Headings

If you wish to include a section link that's not visibly shown within the target element, use Screen Reader .sr-only class from Tailwind.

html
<h2 class="sr-only">Include Me!</h2>

Sticky Positioning

See Tailwind's documentation on sticky positioning if you wish to keep the Table of Contents component visible during scrolling.