I want to make an animation of type writer so when it reaches the last world it just delete everything and start over. so what can I do to make it simple ?
<body>
<h1 id="main-text">
<span id="sp1"></span>
</h1>
<script>
let mainText = document.getElementById("main-text");
let txt1 = "this is the main text!!!";
let sp1 = document.getElementById("sp1");
let cnt = 0;
let txt1Handle = document.getElementById(txt1);
let myInterval = setInterval(() => {
let letter = document.createTextNode(txt1[cnt]);
sp1.appendChild(letter);
cnt++;
console.log(cnt);
if (cnt >= txt1.length) {
cnt = 0;
clearInterval(myInterval);
}
}, 200);
</script>
</body>
2
Answers
Is this what you were looking for? You could even add a small delay inbetween swapping the texts so users have more of a chance to read it.
setInterval
, usesetTimeout
that recalls an innertype
function. That way you can wait longer once a text is fully typed for a better UXcharIndex
) and useNode.textContent
to print it as the element’s text%
to loop the text index back to0
For completeness, "simple" – but unsure if that’s exactly the desired… here’s the simple: