Skip to content

Instantly share code, notes, and snippets.

@softplus
Created Apr 25, 2021
Embed
What would you like to do?
Dynamic table of contents with Intersection Observer
<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>
@softplus
Copy link
Author

softplus commented Apr 25, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment