Skip to content

Instantly share code, notes, and snippets.

@GrantCuster
Created October 25, 2019 13:47
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 GrantCuster/4491ee3801357a7f3dd58af6cb35b2cc to your computer and use it in GitHub Desktop.
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.
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