diff --git a/layouts/partials/toc.html b/layouts/partials/toc.html
index 959347ac..35393cdd 100644
--- a/layouts/partials/toc.html
+++ b/layouts/partials/toc.html
@@ -33,11 +33,16 @@
function getActiveAnchorId(anchors, offsetRatio) {
const threshold = window.scrollY + window.innerHeight * offsetRatio
+ const tocLinks = [...document.querySelectorAll('#TableOfContents a[href^="#"]')]
+ const tocIds = new Set(tocLinks.map(link => link.getAttribute('href').substring(1)))
+
for (let i = anchors.length - 1; i >= 0; i--) {
const top = anchors[i].getBoundingClientRect().top + window.scrollY
- if (top <= threshold) return anchors[i].id
+ if (top <= threshold && tocIds.has(anchors[i].id)) {
+ return anchors[i].id
+ }
}
- return anchors[0]?.id || ''
+ return anchors.find(anchor => tocIds.has(anchor.id))?.id || ''
}
function updateTOC({ toc, anchors, links, scrollOffset, collapseInactive }) {