Skip to content

Instantly share code, notes, and snippets.

@softplus
Created April 25, 2021 17:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save softplus/240350191db1d3eddebb4159693f60d9 to your computer and use it in GitHub Desktop.
Save softplus/240350191db1d3eddebb4159693f60d9 to your computer and use it in GitHub Desktop.
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

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