-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfadein-fadeout-plainjs-requestanimationframe.js
52 lines (45 loc) · 1.2 KB
/
fadein-fadeout-plainjs-requestanimationframe.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
// fade in element
const fadeIn = (el, smooth = true, displayStyle = 'block') => {
el.style.opacity = 0;
el.style.display = displayStyle;
if (smooth) {
let opacity = 0;
let request;
const animation = () => {
el.style.opacity = opacity += 0.04;
if (opacity >= 1) {
opacity = 1;
cancelAnimationFrame(request);
}
};
const rAf = () => {
request = requestAnimationFrame(rAf);
animation();
};
rAf();
} else {
el.style.opacity = 1;
}
};
// fade out element
const fadeOut = (el, smooth = true, displayStyle = 'none') => {
if (smooth) {
let opacity = el.style.opacity;
let request;
const animation = () => {
el.style.opacity = opacity -= 0.04;
if (opacity <= 0) {
opacity = 0;
el.style.display = displayStyle;
cancelAnimationFrame(request);
}
};
const rAf = () => {
request = requestAnimationFrame(rAf);
animation();
};
rAf();
} else {
el.style.opacity = 0;
}
};