I have a problem with an animation that I am trying to insert into my website.
I have written the following JavaScript. Basically what it does is append a letter every few seconds.
function typeText(element, elementText, index = 0) {
if (index < elementText.length) {
element.textContent += elementText.charAt(index);
index++;
const typingSpeed = Math.floor(Math.random() * 100) + 30;
setTimeout(() => typeText(element, elementText, index), typingSpeed);
}
}
It works fine until I have an html tag nested inside another html tag. Something like this:
<h2> Some text <span class="blue-text"> some more text </span> </h2>
What happens is that "some text" is written correctly but when the span is about to be written, the typewriter slows down for a few seconds and deletes the span tag with all the associated styles and then writes the rest of the text.
What I need is for the function to preserve the HTML. I don't know how to solve it and a CSS approach will not work because the way of doing a writing animation is not responsive.
I think that it would be a better idea to make a CSS animation rather than writing the code for the animation in js.
here's an example of a CSS animation
<html>
<head>
<style>
#div{
position: absolute;
animation: anim 3s infinite linear;
background-color: black;
width: 300px;
height: 300px;
}
@keyframes anim {
0%{left: 0%;}
100%{left: 80%;}
}
</style>
</head>
<body>
<div id="div"></div>
</body>