Reputation: 27
I am trying to use the auto text on javascript, but it does not count the spaces between the letters, the final result is "Hellotheremynameis" instead of "Hello there my name is"
const p = document.getElementById("text");
let index = 0;
const write = "Hello there my name is";
//auto text
function autoWrite() {
if (index < write.length) {
p.innerText += write.charAt(index);
index++;
}
}
Upvotes: 0
Views: 239
Reputation: 1293
There are two problems here:
First, you used if
instead of while
. Though, you can use if
here, but have to make the function recursive by calling the function after the incrementation:
function autoWrite() {
if (index < write.length) {
p.innerText += write.charAt(index);
index++;
autoWrite();
}
}
Second problem is: you used .innerText
which will igonre the whitespace. So you need to use .innerHTML
.
function autoWrite() {
while (index < write.length) {
p.innerHTML += write.charAt(index);
index++;
}
}
Try this...
Upvotes: 1
Reputation: 84
You need to use a loop, to go through every character in the string.
const p = document.getElementById("text");
let index = 0;
const write = "Hello there my name is";
//auto text
function autoWrite() {
while (index < write.length) {
p.innerText += write.charAt(index);
index++;
}
}
Upvotes: 0