|
| 1 | +document.addEventListener("DOMContentLoaded", () => { |
| 2 | + const SCROLL_OFFSET = 70; // Adjust based on your header height |
| 3 | + const TOC_SELECTOR_LEFT = '.md-nav__link'; // Left nav links |
| 4 | + const TOC_SELECTOR_RIGHT = '.md-nav__item--active ~ .md-nav__link'; // Adjust for right nav if you have one |
| 5 | + |
| 6 | + // Smooth scroll with offset |
| 7 | + function scrollToHash(hash) { |
| 8 | + const target = document.querySelector(hash); |
| 9 | + if (!target) return; |
| 10 | + |
| 11 | + const targetPosition = target.getBoundingClientRect().top + window.pageYOffset - SCROLL_OFFSET; |
| 12 | + |
| 13 | + window.scrollTo({ |
| 14 | + top: targetPosition, |
| 15 | + behavior: 'auto' |
| 16 | + }); |
| 17 | + } |
| 18 | + |
| 19 | + // Update active TOC link |
| 20 | + function updateTOC() { |
| 21 | + const headings = document.querySelectorAll('.md-content__inner h1, .md-content__inner h2, .md-content__inner h3'); |
| 22 | + const scrollPosition = window.scrollY + SCROLL_OFFSET + 5; // small buffer |
| 23 | + |
| 24 | + let activeHeading = headings[0]; |
| 25 | + |
| 26 | + for (const heading of headings) { |
| 27 | + if (heading.offsetTop <= scrollPosition) { |
| 28 | + activeHeading = heading; |
| 29 | + } else { |
| 30 | + break; |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + // Left nav |
| 35 | + document.querySelectorAll(TOC_SELECTOR_LEFT).forEach(link => { |
| 36 | + link.classList.remove('md-nav__link--active'); |
| 37 | + if (link.getAttribute('href') === `#${activeHeading.id}`) { |
| 38 | + link.classList.add('md-nav__link--active'); |
| 39 | + } |
| 40 | + }); |
| 41 | + |
| 42 | + // Right nav (optional) |
| 43 | + document.querySelectorAll(TOC_SELECTOR_RIGHT).forEach(link => { |
| 44 | + link.classList.remove('md-nav__link--active'); |
| 45 | + if (link.getAttribute('href') === `#${activeHeading.id}`) { |
| 46 | + link.classList.add('md-nav__link--active'); |
| 47 | + } |
| 48 | + }); |
| 49 | + } |
| 50 | + |
| 51 | + // On page load, scroll to hash correctly |
| 52 | + if (window.location.hash) { |
| 53 | + scrollToHash(window.location.hash); |
| 54 | + } |
| 55 | + |
| 56 | + // Handle clicks on anchor links |
| 57 | + document.querySelectorAll('a[href^="#"]').forEach(anchor => { |
| 58 | + anchor.addEventListener('click', function (e) { |
| 59 | + e.preventDefault(); |
| 60 | + const hash = this.getAttribute('href'); |
| 61 | + history.pushState(null, null, hash); |
| 62 | + scrollToHash(hash); |
| 63 | + updateTOC(); |
| 64 | + }); |
| 65 | + }); |
| 66 | + |
| 67 | + // Update TOC on scroll |
| 68 | + window.addEventListener('scroll', updateTOC); |
| 69 | + |
| 70 | + // Triple verification: check periodically in case of delayed rendering |
| 71 | + setInterval(updateTOC, 500); |
| 72 | +}); |
0 commit comments