-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcurrent.js
64 lines (56 loc) · 2.22 KB
/
current.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
const sections = document.querySelectorAll("section");
const links = document.querySelectorAll("nav li a");
let currentSection = sections[0];
//console.log(currentSection);
let currentLink = links[0];
let currentIndex = 0;
let initialPosition = window.scrollY;
window.addEventListener("load", () => {
let loadedHeight = window.scrollY;
let height = 0;
let index;
for (let i=0; i<sections.length; i+=1) {
height += sections[i].offsetHeight;
if (height >= loadedHeight) {
index = i;
break;
}
}
currentIndex = index;
currentLink.parentNode.classList.remove("current-page");
currentLink = links[index];
currentLink.parentNode.classList.add("current-page");
currentSection = sections[index];
if (index == 0) { initialPosition = 0; }
else { initialPosition = height - sections[index].offsetHeight; }
});
window.addEventListener("scroll", () => {
try {
let currentPosition = window.scrollY;
//console.log("CP", currentPosition);
if (currentPosition > (initialPosition + currentSection.offsetHeight - 25)) {
currentLink.parentNode.classList.remove("current-page");
let next = links[(currentIndex+1)%links.length];
next.parentNode.classList.add("current-page");
currentSection = sections[(currentIndex+1)%sections.length];
currentLink = next;
//console.log(currentLink);
initialPosition = currentPosition;
//console.log("IP", initialPosition)
currentIndex += 1;
}
else if (currentPosition < initialPosition) {
currentLink.parentNode.classList.remove("current-page");
let previous = links[(currentIndex-1)%links.length];
//console.log(previous);
previous.parentNode.classList.add("current-page");
currentSection = sections[(currentIndex-1)%sections.length];
initialPosition = currentPosition - currentSection.offsetHeight;
currentLink = previous;
currentIndex -= 1;
}
}
catch (exception) {
console.log(exception);
}
});