1
0
Fork 0
mirror of https://git.sr.ht/~ashkeel/strimertul-website synced 2024-10-31 21:33:09 +00:00
strimertul-website/static/script/toc.js
2023-03-01 14:17:50 +01:00

34 lines
932 B
JavaScript

const toc = document.getElementById("TableOfContents");
const getId = (el) => {
do {
const id = el.getAttribute("id");
if (id) {
return id;
}
el = el.previousElementSibling;
} while (el);
};
if (toc) {
if (toc.children.length < 1) {
toc.parentElement.remove();
} else {
const observer = new IntersectionObserver((entries) => {
const filtered = entries.filter((i) => getId(i.target));
filtered.forEach((entry) => {
const id = getId(entry.target);
if (id && entry.intersectionRatio > 0) {
toc.querySelector(`li.active`)?.classList.remove("active");
toc
.querySelector(`li a[href="#${id}"]`)
.parentElement.classList.add("active");
}
});
});
// Track all sections that have an `id` applied
document.querySelectorAll(".copy *").forEach((section) => {
observer.observe(section);
});
}
}