Han.js is a lightweight, customizable JavaScript plugin for generating scroll-synced table of contents. It automatically detects headings in your article and creates a navigable TOC with active state highlighting.
npm install han-js
<script src="https://cdn.jsdelivr.net/gh/hanluim/han@main/han.js"></script>
To use Han.js, you need to initialize it by passing the selectors for your article container and TOC container.
const toc = new HanluTableOfContents('#article-container', '#toc-container');
You can customize the behavior of Han.js by passing an options object:
const toc = new HanluTableOfContents('#article-container', '#toc-container', {
headingTags: ['H1', 'H2'],
offsetScroll: 50,
linkClassPrefix: 'custom-toc-style-',
activeClass: 'custom-active',
idPrefix: 'custom-id-'
});
Here is a complete example demonstrating how to use Han.js in a webpage.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Example Article</title>
<style>
.custom-active {
font-weight: bold;
color: red;
}
.custom-toc-style-1 {
margin-left: 0;
}
.custom-toc-style-2 {
margin-left: 20px;
}
</style>
</head>
<body>
<div id="toc-container">
<!-- Table of Contents will be generated here -->
</div>
<div id="article-container">
<h1>Introduction</h1>
<p>This is the introduction paragraph.</p>
<h2>Section 1</h2>
<p>This is the first section.</p>
<h2>Section 2</h2>
<p>This is the second section.</p>
<h3>Subsection 2.1</h3>
<p>This is a subsection.</p>
</div>
<script src="han.js"></script>
<script>
const toc = new HanluTableOfContents('#article-container', '#toc-container', {
headingTags: ['H1', 'H2', 'H3'],
offsetScroll: 50,
linkClassPrefix: 'custom-toc-style-',
activeClass: 'custom-active',
idPrefix: 'custom-id-'
});
</script>
</body>
</html>
If you have any questions or need help, feel free to reach out.
Email: hanlu2611@gmail.com