I made a text animation in JavaScript (JS) where the word that is hovered over changes color letter by letter over time. I only want the text animation to reset when the word isn't being hovered over anymore.
However, when I am hovering over the word and I move my cursor over a different letter in the word the hovering animation resets. Can someone explain why it does this and how I may be able to fix this?
const home = document.querySelector("#home");
const homeText = home.textContent;
const splitHomeText = homeText.split("");
home.textContent = "";
for (let i = 0; i < splitHomeText.length; i++) {
home.innerHTML += "<span>" + splitHomeText[i] + "</span>";
}
let char = 0;
let timer = null;
home.addEventListener("mouseover", highlight);
home.addEventListener("mouseout", clear);
function highlight() {
timer = setInterval(onTickHome, 50);
}
function onTickHome() {
const span = home.querySelectorAll("span")[char];
span.classList.add("highlight");
char++;
if (char === splitHomeText.length) {
complete();
return;
}
}
function complete() {
char = 0;
clearInterval(timer);
}
function clear() {
char = 0;
clearInterval(timer);
for (let i = 0; i < splitHomeText.length; i++) {
const span = home.querySelectorAll("span")[i];
span.classList.remove("highlight");
}
}
#home {
text-decoration: none;
color: black;
font-size: 30px;
}
.highlight {
color: #EF233C;
}
<a href="#" id="home">Home</a>