An open API service indexing awesome lists of open source software.

https://github.com/oom-components/toc

Web component to create a table of content
https://github.com/oom-components/toc

Last synced: 10 months ago
JSON representation

Web component to create a table of content

Awesome Lists containing this project

README

          

# Table of contents

Web component to create a table of contents.

- No dependencies
- Very light
- Follow the **progressive enhancement strategy**. If JavaScript fails the page
continue working.
- No styles or themes are provided with this package.
- Build with modern JavaScript.

## Usage

Import and register the component with the desired tag name:

```js
import Toc from "toc/toc.js";

customElements.define("oom-toc", Toc);
```

Use it in the HTML code. The `data-target` attribute must contain the id of the
text container:

```html

Table of contents


Fallback text if something fails


Lorem Ipsum Dolor Sit Amet


...

Consectetur Adipiscing


...

```

## Anchors

Anchors are created automatically if they are missing. For example:

```html

One


Two


Three


```

The component makes the following changes:

```html

One


Two


Three


```

- It creates the id automatically using the text content of the heading.
- It creates the anchor automatically if it's missing
- If the id and/or anchor is detected, it does nothing.

If you want a different anchor style, you can override the `anchorCreator`
static property:

```js
import Toc from "toc/toc.js";

//


anchorHeader


Toc.anchorCreator = (heading, id) => {
const a = document.createElement("a");
a.href = `#${id}`;
a.innerHTML = "anchor";
heading.prepend(a);
};

customElements.define("oom-toc", Toc);
```