const sections = document.querySelectorAll('.legal-section[id]'); const tocLinks = document.querySelectorAll('.legal-toc-link'); let pinnedId = null; function getScrollId() { let current = null; sections.forEach(s => { if (s.getBoundingClientRect().top <= 100) current = s; }); return current ? current.id : null; } function setActive(id) { tocLinks.forEach(l => l.classList.remove('active')); if (id) { const link = document.querySelector(`.legal-toc-link[href="#${id}"]`); if (link) link.classList.add('active'); } } function updateActiveToc() { const scrollId = getScrollId(); // Clear pin if the user has scrolled back up - i.e. the scroll-detected section // now comes before the pinned one in the DOM if (pinnedId && scrollId && scrollId !== pinnedId) { const pinnedEl = document.getElementById(pinnedId); const scrollEl = document.getElementById(scrollId); if (pinnedEl && scrollEl && scrollEl.compareDocumentPosition(pinnedEl) & Node.DOCUMENT_POSITION_FOLLOWING) { pinnedId = null; } } setActive(pinnedId || scrollId); } // On click: pin that section so it stays active even if scroll can't reach it tocLinks.forEach(link => { link.addEventListener('click', () => { pinnedId = link.getAttribute('href').substring(1); setActive(pinnedId); }); }); let ticking = false; window.addEventListener('scroll', () => { if (!ticking) { requestAnimationFrame(() => { updateActiveToc(); ticking = false; }); ticking = true; } }); updateActiveToc();