-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfade.js
44 lines (39 loc) · 1.56 KB
/
fade.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
//Get elements from DOM and push into array
const faders = document.getElementsByClassName("fade");
const initialFadersArr = [];
for (let i = 0; i < faders.length; i++) {
initialFadersArr.push(faders[i]);
}
//Function to control fade-in effect
const animateThese = arr => {
let viewPortHeight = window.visualViewport.height;
arr.forEach(element => {
let rect = element.getBoundingClientRect();
let elemOpacity = element.style.opacity;
let animation = element.getAnimations({ subtree: true })[0];
console.log(animation);
if (rect.y > viewPortHeight || rect.bottom < 0) {
//Cancel animation if element is not in viewport and ensure it stays invisible
animation.finish();
let elemOpacity = element.style.opacity = 0;
} else if (rect.y < viewPortHeight && elemOpacity == 0) {
//Play animation if element is in viewport and invisible and reset opacity value
animation.play();
let elemOpacity = element.style.opacity = 1;
}
});
};
//Functions to select elements to animate
const initialFadeIn = () => {
animateThese(initialFadersArr);
};
const fadeIn = () => {
let hiddenFaders = initialFadersArr.filter(element => element.style.opacity < 1);
animateThese(hiddenFaders);
if (hiddenFaders[0] == undefined) {
document.removeEventListener("scroll", fadeIn);
}
};
//Event listeners to trigger animations on initial page load and on scrolls
window.addEventListener("load", initialFadeIn);
document.addEventListener("scroll", fadeIn);