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

42 lines
1.1 KiB
JavaScript
Raw Normal View History

2023-03-01 13:17:50 +00:00
const toc = document.getElementById("TableOfContents");
2023-04-05 16:04:48 +00:00
const getHeaderId = (el) => {
2023-03-01 13:17:50 +00:00
do {
2023-04-05 16:04:48 +00:00
if (el.nodeName === "H1" || el.nodeName === "H2" || el.nodeName === "H3") {
const id = el.getAttribute("id");
if (id) {
return id;
}
2023-03-01 13:17:50 +00:00
}
el = el.previousElementSibling;
} while (el);
};
if (toc) {
if (toc.children.length < 1) {
toc.parentElement.remove();
} else {
const observer = new IntersectionObserver((entries) => {
2023-03-01 13:20:15 +00:00
const filtered = entries.filter(
2023-04-05 16:04:48 +00:00
(i) => getHeaderId(i.target) && i.intersectionRatio > 0
2023-03-01 13:20:15 +00:00
);
if (filtered.length > 0) {
2023-03-01 13:21:07 +00:00
toc
.querySelectorAll(`li.active`)
.forEach((entry) => entry.classList.remove("active"));
2023-04-05 16:04:48 +00:00
2023-03-01 13:20:15 +00:00
filtered.forEach((entry) => {
2023-04-05 16:04:48 +00:00
const id = getHeaderId(entry.target);
2023-03-01 13:17:50 +00:00
toc
.querySelector(`li a[href="#${id}"]`)
.parentElement.classList.add("active");
2023-03-01 13:20:15 +00:00
});
}
2023-03-01 13:17:50 +00:00
});
// Track all sections that have an `id` applied
document.querySelectorAll(".copy *").forEach((section) => {
observer.observe(section);
});
}
}