📑 Table of Contents Widget Design
Table of Contents (TOC) widgets є essential navigation tool для long-form articles, guides, та educational content. Sticky TOC lets readers quickly jump між sections, understand article structure at a glance, та track reading progress through active highlighting. Для mushroom cultivation guides або species profiles (often 3000+ words), TOC significantly improves UX. Цей guide охоплює auto-generation від headings, sticky positioning, scroll spy logic, та responsive behavior.
🎨 TOC Design Patterns
Introduction
PF Tek (Psilocybe Fanaticus Technique) є beginner-friendly method...
Materials Needed
• Brown rice flour • Vermiculite • Water...
Step 1: Sterilization
Prepare sterilization chamber з pressure cooker...
(Content demonstration)
💡 TOC Best Practices:
- ✅ Generate automatically від H2/H3 headings
- ✅ Sticky positioning (stays visible on scroll)
- ✅ Active highlighting (current section)
- ✅ Smooth scroll on link click
- ✅ Collapse на mobile (accordion або hide)
- ✅ Max 8-10 items (Don't overwhelm)
- ✅ Progress indicator (optional)
💻 Complete Implementation
HTML Structure:
<!-- Article Layout -->
<div class="article-layout">
<!-- Table of Contents Sidebar -->
<aside class="toc-sidebar">
<div class="toc-header">
<h3 class="toc-title">📑 On This Page</h3>
</div>
<nav class="toc-nav" aria-label="Table of contents">
<ul class="toc-list" id="tocList">
<!-- Auto-generated від JavaScript -->
</ul>
</nav>
</aside>
<!-- Main Article Content -->
<article class="article-content">
<h1>PF Tek Cultivation Guide</h1>
<h2 id="introduction">Introduction</h2>
<p>Content here...</p>
<h2 id="materials">Materials Needed</h2>
<p>Content here...</p>
<h3 id="equipment">Essential Equipment</h3>
<p>Sub-section content...</p>
<h2 id="process">Step-by-Step Process</h2>
<!-- More sections -->
</article>
</div>
CSS Styling:
/* Article Grid Layout */
.article-layout {
display: grid;
grid-template-columns: 250px 1fr;
gap: 40px;
max-width: 1200px;
margin: 0 auto;
padding: 40px 20px;
}
/* TOC Sidebar */
.toc-sidebar {
position: sticky;
top: 80px; /* Account для sticky header */
align-self: start;
background: white;
border: 2px solid #e9ecef;
border-radius: 12px;
padding: 20px;
max-height: calc(100vh - 100px);
overflow-y: auto;
}
.toc-title {
font-size: 1.1em;
font-weight: 700;
color: #2c3e50;
margin-bottom: 15px;
padding-bottom: 10px;
border-bottom: 2px solid #e9ecef;
}
/* TOC List */
.toc-list {
list-style: none;
padding: 0;
margin: 0;
}
.toc-list li {
margin: 0;
}
.toc-list a {
display: block;
padding: 8px 12px;
color: #6c757d;
text-decoration: none;
font-size: 0.95em;
border-left: 3px solid transparent;
transition: all 0.2s;
}
.toc-list a:hover {
color: #43e97b;
border-left-color: #43e97b;
background: #f8f9fa;
}
.toc-list a.active {
color: #43e97b;
background: #e0fef1;
border-left-color: #43e97b;
font-weight: 600;
}
/* Nested Items (H3) */
.toc-list li.toc-h3 {
padding-left: 15px;
}
.toc-list li.toc-h3 a {
font-size: 0.9em;
color: #8e9aaf;
}
/* Article Content */
.article-content {
background: white;
padding: 40px;
border: 2px solid #e9ecef;
border-radius: 12px;
}
/* Smooth scroll padding (для sticky header) */
html {
scroll-padding-top: 100px;
}
/* Responsive */
@media (max-width: 1024px) {
.article-layout {
grid-template-columns: 1fr;
}
.toc-sidebar {
position: static;
max-height: none;
order: -1; /* Place TOC före content на mobile */
}
}
JavaScript Auto-Generation & Scroll Spy:
// Table of Contents Generator
class TableOfContents {
constructor(contentSelector, tocSelector) {
this.content = document.querySelector(contentSelector);
this.tocList = document.querySelector(tocSelector);
this.headings = [];
this.activeIndex = 0;
this.init();
}
init() {
this.generateTOC();
this.setupScrollSpy();
this.setupSmoothScroll();
}
generateTOC() {
// Find all H2 та H3 headings у content
this.headings = Array.from(
this.content.querySelectorAll('h2, h3')
).filter(heading => heading.id); // Only headings з IDs
if (this.headings.length === 0) {
console.warn('No headings з IDs found');
return;
}
// Build TOC HTML
const tocHTML = this.headings.map((heading, index) => {
const level = heading.tagName.toLowerCase();
const text = heading.textContent;
const id = heading.id;
const className = level === 'h3' ? 'toc-h3' : '';
return `
<li class="${className}">
<a href="#${id}" data-index="${index}">
${text}
</a>
</li>
`;
}).join('');
this.tocList.innerHTML = tocHTML;
}
setupScrollSpy() {
// Intersection Observer для active highlighting
const observerOptions = {
rootMargin: '-100px 0px -66%',
threshold: 0
};
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const index = this.headings.indexOf(entry.target);
this.setActiveItem(index);
}
});
}, observerOptions);
// Observe all headings
this.headings.forEach(heading => observer.observe(heading));
}
setActiveItem(index) {
if (index === this.activeIndex) return;
this.activeIndex = index;
// Update active class
const links = this.tocList.querySelectorAll('a');
links.forEach((link, i) => {
link.classList.toggle('active', i === index);
});
// Scroll TOC item into view (if needed)
const activeLink = links[index];
if (activeLink) {
activeLink.scrollIntoView({
behavior: 'smooth',
block: 'nearest'
});
}
}
setupSmoothScroll() {
// Smooth scroll on link click
this.tocList.addEventListener('click', (e) => {
if (e.target.tagName === 'A') {
e.preventDefault();
const targetId = e.target.getAttribute('href').slice(1);
const targetEl = document.getElementById(targetId);
if (targetEl) {
targetEl.scrollIntoView({
behavior: 'smooth',
block: 'start'
});
// Update URL (optional)
history.pushState(null, null, `#${targetId}`);
}
}
});
}
}
// Initialize on DOM ready
document.addEventListener('DOMContentLoaded', () => {
new TableOfContents('.article-content', '#tocList');
});
⚡ Advanced Features
1. Progress Indicator
Visual bar showing reading progress:
<div class="toc-progress">
<div class="progress-bar"></div>
</div>
// JavaScript
const progress = (scrolled / total) * 100;
progressBar.style.width = `${progress}%`;
2. Collapsible Sections
Nested headings can collapse:
<li>
<button class="toc-toggle">▼</button>
<a href="#section">Section</a>
<ul><!-- Nested items --></ul>
</li>
3. Estimated Read Time
Show time для each section:
const wordCount = section.textContent
.split(/\s+/).length;
const readTime = Math.ceil(wordCount / 200);
// Display: "3 min"
4. Mobile Dropdown
Convert to dropdown select на mobile:
@media (max-width: 768px) {
.toc-sidebar {
display: none;
}
.toc-mobile-dropdown {
display: block;
}
}
✅ TOC Widget Checklist
Implementation Checklist:
- ☐ Auto-generates від H2/H3 headings з IDs
- ☐ Sticky positioning (stays visible)
- ☐ Active section highlighting (Intersection Observer)
- ☐ Smooth scroll on click
- ☐ Keyboard accessible (Tab navigation)
- ☐ ARIA labels (
aria-label="Table of contents") - ☐ Mobile-friendly (collapse або hide)
- ☐ Max-height з scroll (long articles)
- ☐ Visual hierarchy (indent H3)
- ☐ Hover states visible
- ☐ URL updates on click (optional)
- ☐ Works з sticky header (scroll padding)