Dynamic table of contents with Intersection Observer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script type="text/javascript"> | |
// Intersection Observer Options | |
var myObserverOptions = { | |
root: null, | |
rootMargin: "0px", | |
threshold: [1], | |
}; | |
// Each Intersection Observer runs setCurrent | |
var observeHtags = new IntersectionObserver(setCurrent, myObserverOptions); | |
// Add IO to all headings | |
function addIntersectionObserver() { | |
var allHtags = document.querySelectorAll(".article-entry > h1, .article-entry > h2, .article-entry > h3"); | |
allHtags.forEach(tag => { | |
observeHtags.observe(tag); | |
}); | |
} | |
// runs when the Intersection Observer is sent | |
function setCurrent(e) { | |
e.map(i => { | |
if (i.isIntersecting === true) { | |
document.querySelector(`a[href="#${i.target.id}"]`).classList.add("active"); | |
} else { | |
document.querySelector(`a[href="#${i.target.id}"]`).classList.remove("active"); | |
} | |
}) | |
} | |
(function setUp() { | |
addIntersectionObserver(); | |
document.getElementsByClassName('article-toc')[0].style.display = ''; | |
})(); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Documented at https://johnmu.com/dynamic-toc-io/