diff options
author | Xavier Valls Pla <xaviervallspla@gmail.com> | 2020-06-25 16:56:49 +0300 |
---|---|---|
committer | Xavier Valls Pla <xaviervallspla@gmail.com> | 2020-06-25 16:56:49 +0300 |
commit | 9dcdacfd2eac107f851f469c18d3506ea255ee8c (patch) | |
tree | 0d6b12e4de4f2207a93a3a73835b5b8fe07967ea | |
parent | 74c0fe909401234cdf75d780db2bb4250697b03e (diff) |
simplify toc and remove post title from it
Highlight all sections on sight instead of last one to intersect
-rw-r--r-- | static/js/table-of-contents.js | 37 |
1 files changed, 6 insertions, 31 deletions
diff --git a/static/js/table-of-contents.js b/static/js/table-of-contents.js index 55f1ecb..911adbf 100644 --- a/static/js/table-of-contents.js +++ b/static/js/table-of-contents.js @@ -1,29 +1,13 @@ -function elementInToC(entry) { - return document.querySelector(`#TableOfContents ul li a[href="#${entry.target.getAttribute('id')}"]`); -} - window.addEventListener('DOMContentLoaded', () => { - var previousActive = null; - const observer = new IntersectionObserver(entries => { - var foundActive = false; entries.forEach(entry => { - if (!foundActive && entry.isIntersecting) { - if (previousActive) { - previousActive.classList.remove('active'); - } - elementInToC(entry).classList.add('active'); - foundActive = true; - previousActive = elementInToC(entry); - } - else { - elementInToC(entry).classList.remove('active'); + const id = entry.target.getAttribute('id'); + if (entry.intersectionRatio > 0) { + document.querySelector(`#TableOfContents ul li a[href="#${id}"]`).classList.add('active'); + } else { + document.querySelector(`#TableOfContents ul li a[href="#${id}"]`).classList.remove('active'); } - }) - - if (!foundActive) { - previousActive.classList.add('active'); - }; + }); }); // Track all headers that have an `id` applied @@ -31,12 +15,3 @@ window.addEventListener('DOMContentLoaded', () => { observer.observe(section); }); }); - -// Post title doesn't get parsed as it is not part of the content file -(function addPostTitle2ToC() { - var toc = document.getElementById('TableOfContents'); - if (!toc) return; - var title = document.getElementById("post__title").innerText; - var ul = toc.querySelector('ul'); - ul.outerHTML = `<ul><li><a href="#post__title" class="active">${title}</a>${ul.outerHTML}</li></ul>`; -})(); |