2023-03-18 14:55:36 +08:00
|
|
|
// src: https://github.com/JorelAli/mdBook-pagetoc
|
|
|
|
|
2023-03-11 15:20:06 +08:00
|
|
|
// Un-active everything when you click it
|
2023-03-18 14:55:36 +08:00
|
|
|
Array.prototype.forEach.call(document.getElementsByClassName("pagetoc")[0].children, function(el, i) {
|
2023-03-11 15:20:06 +08:00
|
|
|
el.addEventHandler("click", function() {
|
2023-03-18 14:55:36 +08:00
|
|
|
Array.prototype.forEach.call(document.getElementsByClassName("pagetoc")[0].children, function(el, i) {
|
2023-03-11 15:20:06 +08:00
|
|
|
el.classList.remove("active");
|
|
|
|
});
|
|
|
|
el.classList.add("active");
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
var updateFunction = function() {
|
|
|
|
|
|
|
|
var id;
|
|
|
|
var elements = document.getElementsByClassName("header");
|
2023-03-18 14:55:36 +08:00
|
|
|
Array.prototype.forEach.call(elements, function(el, i) {
|
2023-03-11 15:20:06 +08:00
|
|
|
if (window.pageYOffset >= el.offsetTop) {
|
|
|
|
id = el;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2023-03-18 14:55:36 +08:00
|
|
|
Array.prototype.forEach.call(document.getElementsByClassName("pagetoc")[0].children, function(el, i) {
|
2023-03-11 15:20:06 +08:00
|
|
|
el.classList.remove("active");
|
|
|
|
});
|
2023-03-18 14:55:36 +08:00
|
|
|
|
|
|
|
Array.prototype.forEach.call(document.getElementsByClassName("pagetoc")[0].children, function(el, i) {
|
2023-03-11 15:20:06 +08:00
|
|
|
if (id.href.localeCompare(el.href) == 0) {
|
|
|
|
el.classList.add("active");
|
|
|
|
}
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
// Populate sidebar on load
|
|
|
|
window.addEventListener('load', function() {
|
|
|
|
var pagetoc = document.getElementsByClassName("pagetoc")[0];
|
|
|
|
var elements = document.getElementsByClassName("header");
|
2023-03-18 14:55:36 +08:00
|
|
|
Array.prototype.forEach.call(elements, function(el, i) {
|
2023-03-11 15:20:06 +08:00
|
|
|
var link = document.createElement("a");
|
2023-03-18 14:55:36 +08:00
|
|
|
|
|
|
|
// Indent shows hierarchy
|
|
|
|
var indent = "";
|
|
|
|
switch (el.parentElement.tagName) {
|
|
|
|
case "H2":
|
|
|
|
indent = "20px";
|
|
|
|
break;
|
|
|
|
case "H3":
|
|
|
|
indent = "40px";
|
|
|
|
break;
|
|
|
|
case "H4":
|
|
|
|
indent = "60px";
|
|
|
|
break;
|
|
|
|
default:
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
2023-03-11 15:20:06 +08:00
|
|
|
link.appendChild(document.createTextNode(el.text));
|
2023-03-18 14:55:36 +08:00
|
|
|
link.style.paddingLeft = indent;
|
2023-03-11 15:20:06 +08:00
|
|
|
link.href = el.href;
|
|
|
|
pagetoc.appendChild(link);
|
2023-03-18 14:55:36 +08:00
|
|
|
});
|
2023-03-11 15:20:06 +08:00
|
|
|
updateFunction.call();
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// Handle active elements on scroll
|
|
|
|
window.addEventListener("scroll", updateFunction);
|