Created
October 25, 2019 13:47
-
-
Save GrantCuster/4491ee3801357a7f3dd58af6cb35b2cc to your computer and use it in GitHub Desktop.
Add an active class to the table of contents link when the heading is visible. For me, this was on top of html generated through markdown-it and markdown-it-table-of-contents, but similar things could work in lots of other situations.
This file contains hidden or 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
window.addEventListener( | |
"load", | |
() => { | |
let headings = document.querySelectorAll("h2, h3, h4"); | |
let links = document.querySelectorAll(".table-of-contents ul li a"); | |
observer = new IntersectionObserver( | |
(entry, observer) => { | |
if (entry[0].intersectionRatio === 1) { | |
for (let link of links) { | |
link.className = ""; | |
} | |
let target_id = entry[0].target.getAttribute("id"); | |
let selector = | |
'.table-of-contents ul li a[href="#' + target_id + '"]'; | |
let link = document.querySelector(selector); | |
link.className = "active"; | |
} | |
}, | |
{ threshold: 1, rootMargin: "0px 0px -20% 0px" } | |
); | |
for (let heading of headings) { | |
observer.observe(heading); | |
} | |
}, | |
false | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment