summaryrefslogtreecommitdiff
path: root/layouts/_partials/scripts/toc-js.html
diff options
context:
space:
mode:
authorEltrac <hi@guhub.cn>2025-07-18 18:46:45 +0800
committerEltrac <hi@guhub.cn>2025-07-18 18:46:45 +0800
commit8e2c6660687062c9ad88402fa746fcf611bfe846 (patch)
tree83d44f5645e49d3bfc948d0aa0ecc399c4fe3cab /layouts/_partials/scripts/toc-js.html
parent35a061e5fb7c7c4c3b3f7a5e8d6c981ee5aa86f4 (diff)
refactor: make partials of all embeded JavaScript code
Former-commit-id: 70cfd74bcfab6a74dd9755c1946109e6576158a8
Diffstat (limited to 'layouts/_partials/scripts/toc-js.html')
-rw-r--r--layouts/_partials/scripts/toc-js.html41
1 files changed, 41 insertions, 0 deletions
diff --git a/layouts/_partials/scripts/toc-js.html b/layouts/_partials/scripts/toc-js.html
new file mode 100644
index 00000000..110f2357
--- /dev/null
+++ b/layouts/_partials/scripts/toc-js.html
@@ -0,0 +1,41 @@
+{{ if .Params.toc }}
+<script>
+document.addEventListener('DOMContentLoaded', () => {
+ const toc = document.getElementById('toc');
+ if (!toc) return;
+
+ const headings = document.querySelectorAll('h2, h3');
+ const observer = new IntersectionObserver(entries => {
+ entries.forEach(entry => {
+ if (!entry.isIntersecting) return;
+
+ const id = entry.target.id;
+ const tocLink = toc.querySelector(`a[href="#${id}"]`);
+ if (!tocLink) return;
+
+ const listItem = tocLink.parentElement;
+ const isH2 = entry.target.tagName === 'H2';
+
+ // Clear all active states when a new H2 is encountered
+ if (isH2) {
+ toc.querySelectorAll('li.active').forEach(el => el.classList.remove('active'));
+ }
+
+ // Set current item as active
+ listItem.classList.add('active');
+
+ // If this is an H3, find and activate its parent H2
+ if (!isH2) {
+ const parentH2Item = listItem.closest('ul').previousElementSibling?.closest('li');
+ if (parentH2Item) parentH2Item.classList.add('active');
+ }
+ });
+ }, {
+ rootMargin: '0px 0px -50% 0px',
+ threshold: 0.5
+ });
+
+ headings.forEach(heading => observer.observe(heading));
+});
+</script>
+{{ end }}