forked from 4equest/web_animation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtext_shuffle_hex.js
70 lines (60 loc) · 2.17 KB
/
text_shuffle_hex.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
document.addEventListener("DOMContentLoaded", () => {
const elements = document.querySelectorAll(".shuffle_text_hex");
elements.forEach((element) => {
element.style.opacity = "0";
})
const isInViewport = (element) => {
const rect = element.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
};
const startAnimation = (element) => {
const originalText = element.textContent;
const hexArray = Array.from(originalText).map((char) => char.charCodeAt(0).toString(16).toUpperCase());
element.textContent = "";
element.style.opacity = "1";
let currentIndex = 0;
const animateHex = () => {
if (currentIndex >= hexArray.length) {
element.textContent = originalText;
return;
}
const currentCharHex = hexArray[currentIndex];
let displayIndex = 0;
const hexInterval = setInterval(() => {
if (displayIndex <= currentCharHex.length) {
element.textContent =
originalText.slice(0, currentIndex) +
"" +
currentCharHex.slice(0, displayIndex) +
"".padEnd(originalText.length - currentIndex - 1, " ");
displayIndex+=2;
} else {
clearInterval(hexInterval);
element.textContent =
originalText.slice(0, currentIndex) +
originalText[currentIndex] +
"".padEnd(originalText.length - currentIndex - 1, " ");
currentIndex++;
animateHex();
}
}, 6);
};
animateHex();
};
const handleScroll = () => {
elements.forEach((element) => {
if (!element.dataset.animated && isInViewport(element)) {
element.dataset.animated = "true";
startAnimation(element);
}
});
};
window.addEventListener("scroll", handleScroll);
window.addEventListener("resize", handleScroll);
handleScroll();
});