-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtable-of-contents.js
More file actions
82 lines (71 loc) · 2.02 KB
/
table-of-contents.js
File metadata and controls
82 lines (71 loc) · 2.02 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
var minContentSections = 2
var scrollDuration_ms = 400;
var scrollAnimType = "swing";
$(document).ready(function() {
var headers = getHeaders();
createContents(headers);
showContentsIfPresent(headers);
$(document).on("scroll", updateTocOnScroll(headers));
});
function getHeaders() {
var headers = $("#column").find("H2").toArray();
headers.unshift($(".column-title")[0]);
return headers;
}
function createContents(headers) {
addContentsSection("Introduction", headers[0], headers)
for (var i = 1; i < headers.length; i++) {
addContentsSection(headers[i].innerHTML, headers[i], headers);
}
}
function showContentsIfPresent(headers) {
if (!window.matchMedia("(max-width: 1400px)").matches &&
headers.length > minContentSections) {
$("#table-of-contents").show();
}
}
function updateTocOnScroll(headers) {
return () => {
var active = getActiveSection(headers);
setActiveSection(active);
}
}
function getActiveSection(headers) {
var scroll = $(document).scrollTop();
for (var i = headers.length - 1; i >= 0; i--) {
if (headers[i].offsetTop < scroll) {
return i;
}
}
return -1
}
function setActiveSection(active) {
if (active == -1) { return }
headers = $("#table-of-contents").children();
headers.toggleClass("active-section", false);
$(".content-section:eq(" + active + ")").addClass("active-section");
}
function addContentsSection(sectionTitle, section, headers) {
var newSection = $('<div/>',{
text: sectionTitle,
class: 'content-section'
});
newSection.appendTo('#table-of-contents');
newSection.click(scrollToSection(section, headers));
}
function scrollToSection(section, headers) {
return () => {
$(document).off("scroll");
var animEnd = () => {
$(document).on("scroll", updateTocOnScroll(headers));
updateTocOnScroll(headers)();
};
$('html,body').animate({scrollTop: getSectionY(section)},
scrollDuration_ms, scrollAnimType,
animEnd);
}
}
function getSectionY(section) {
return scrollTo = $(section).offset().top
- $(section).height() - $("#header").height();
}