blog / script.js
Banaxi-Tech's picture
Upload 16 files
81ed537 verified
Raw History Blame Contribute Delete
1.48 kB
// "In this article" contents box, built from the post's h2 headings.
(function () {
var toc = document.querySelector(".toc");
var heads = Array.prototype.filter.call(
document.querySelectorAll(".article h2"),
function (h) { return !h.closest(".stat"); }
);
if (!toc || heads.length < 2) { if (toc) toc.remove(); return; }
var used = {};
var items = heads.map(function (h) {
var id = h.id || h.textContent.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "section";
while (used[id]) id += "-2";
used[id] = true;
h.id = id;
return '<li><a href="#' + id + '">' + h.innerHTML.replace(/<[^>]+>/g, "") + "</a></li>";
});
toc.innerHTML =
'<details open><summary>In this article</summary><ol>' + items.join("") + "</ol></details>";
// Collapsed by default on narrow screens, where the box sits above the text.
var details = toc.querySelector("details");
if (window.matchMedia("(max-width: 72rem)").matches) details.removeAttribute("open");
var links = toc.querySelectorAll("a");
if ("IntersectionObserver" in window) {
var io = new IntersectionObserver(function (entries) {
entries.forEach(function (e) {
if (!e.isIntersecting) return;
links.forEach(function (a) {
a.classList.toggle("on", a.getAttribute("href") === "#" + e.target.id);
});
});
}, { rootMargin: "-80px 0px -70% 0px" });
heads.forEach(function (h) { io.observe(h); });
}
})();