/
reveal-on-scroll.js
73 lines (63 loc) · 1.83 KB
/
reveal-on-scroll.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
69
70
71
72
73
import throttle from "lodash/throttle";
class RevealOnScroll {
constructor(items, thresholdPercent) {
this.thresholdPercent = thresholdPercent / 100;
this.itemsToReveal = items;
this.hideInitially();
this.scrollThrottle = throttle(this.calcCaller, 200).bind(this);
this.events();
}
events() {
window.addEventListener("scroll", this.scrollThrottle);
}
hideInitially() {
this.itemsToReveal.forEach((el) => {
el.classList.add("o-reveal", "o-reveal--is-hidden");
el.isRevealed = false;
});
this.itemsToReveal[this.itemsToReveal.length - 1].isLastItem = true;
}
calcCaller() {
console.log("Scroll function ran");
this.itemsToReveal.forEach((el) => {
if (el.isRevealed) return;
this.calculateIfScrolledTo(el);
});
}
calculateIfScrolledTo(el) {
let revealedItemCoords = this.getCoords(el);
let revealStartingPoint =
revealedItemCoords.top +
revealedItemCoords.height * this.thresholdPercent;
let currentScroll =
window.pageYOffset + document.documentElement.clientHeight;
/*
* When current scroll reaches the top of the revealed items,
* start calculating its coords:
*/
if (currentScroll >= revealedItemCoords.top) {
console.log("Element was calculated");
/*
* Now, we already reach the top of the revealed item,
* plz start revealing our hidden items when current
* scroll reaches again this particular starting point:
*/
if (currentScroll >= revealStartingPoint) {
el.classList.remove("o-reveal--is-hidden");
el.isRevealed = true;
if (el.isLastItem) {
window.removeEventListener("scroll", this.scrollThrottle);
console.log("Event listener was removed");
}
}
}
}
getCoords(el) {
let box = el.getBoundingClientRect();
return {
top: box.top + window.pageYOffset,
height: el.offsetHeight
};
}
}
export default RevealOnScroll;