'How do I make a typing animation?
I've been attempting to create a typing animation program that creates an animation of typing a word. Every period of time (1 second), it adds a letter to the output, seemingly "typing" the word out. Here is my code:
let input = document.querySelector("#input");
let text = document.querySelector("#text");
let run = document.querySelector("#run");
let str = input.value;
run.onclick = function() {
text.innerText = "";
str = input.value;
let chars = [];
for (let i = 0; i < str.length; i++) {
chars[i] = str.charAt(i);
}
for (let i = 0; i < chars.length; i++) {
setTimeout(function() {
text.innerText += chars[i];
}, 1000)
}
}
Solution 1:[1]
Here's one implementation using setInterval
.
As Andy
mentioned in the comments, just search and you'll find plenty of other implementations and answers here at SO.
let input = document.querySelector("#input");
let text = document.querySelector("#text");
let run = document.querySelector("#run");
run.addEventListener("click", function() {
text.innerText = "";
const str = input.value;
const chars = str.split("");
const interval = setInterval(()=>{
if ( !chars.length ){
return clearInterval(interval);
}
text.textContent += chars.shift();
}, 100 );
});
<input id="input" value="Hello world" />
<p id="text"></p>
<button id="run">Run</button>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Kostas Minaidis |