-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathanimations.js
49 lines (40 loc) · 1.11 KB
/
animations.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
// Fading in elements when scrolling
const fadeInElems = document.querySelectorAll('.fade-in');
const debounce = (fn) => {
let frame;
return (...params) => {
if (frame) {
cancelAnimationFrame(frame);
}
frame = requestAnimationFrame(() => {
fn(...params);
});
}
};
const handleScroll = debounce(() => {
const windowHeight = window.innerHeight;
const scrollTop = window.scrollY;
const scrollBottom = scrollTop + windowHeight;
fadeInElems.forEach(elem => {
const top = elem.offsetTop;
const height = elem.offsetHeight;
const bottom = top + height;
const isBeforeBottom = bottom - scrollTop > 0;
const isAfterTop = top < scrollBottom;
if (isBeforeBottom && isAfterTop) {
elem.classList.add('active');
} else {
elem.classList.remove('active');
}
});
});
document.addEventListener('scroll', handleScroll);
//Fade in elements on load
fadeInElems.forEach(elem => {
const isVisible = (elem.offsetTop - window.scrollY) < window.innerHeight;
if (isVisible) {
elem.classList.add('active');
} else {
elem.classList.remove('active');
}
});