-
Notifications
You must be signed in to change notification settings - Fork 4
/
sidebar.js
68 lines (58 loc) · 2.02 KB
/
sidebar.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Un-active everything when you click it
Array.prototype.forEach.call(document.getElementsByClassName("pagetoc")[0].children, function(el, i) {
el.addEventHandler("click", function() {
Array.prototype.forEach.call(document.getElementsByClassName("pagetoc")[0].children, function(el, i) {
el.classList.remove("active");
});
el.classList.add("active");
});
});
var updateFunction = function() {
var id;
var elements = document.getElementsByClassName("header");
Array.prototype.forEach.call(elements, function(el, i) {
if (window.pageYOffset >= el.offsetTop) {
id = el;
}
});
Array.prototype.forEach.call(document.getElementsByClassName("pagetoc")[0].children, function(el, i) {
el.classList.remove("active");
});
Array.prototype.forEach.call(document.getElementsByClassName("pagetoc")[0].children, function(el, i) {
try {
if (id.href.localeCompare(el.href) == 0) {
el.classList.add("active");
}
} catch {}
});
};
// Populate sidebar on load
window.addEventListener('load', function() {
var pagetoc = document.getElementsByClassName("pagetoc")[0];
var elements = document.getElementsByClassName("header");
Array.prototype.forEach.call(elements, function(el, i) {
var link = document.createElement("a");
// 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;
}
link.appendChild(document.createTextNode(el.text));
link.style.paddingLeft = indent;
link.href = el.href;
pagetoc.appendChild(link);
});
updateFunction.call();
});
// Handle active elements on scroll
window.addEventListener("scroll", updateFunction);