ricky
ricky

Reputation: 27

auto-text with javascript

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

Answers (2)

Shuvo
Shuvo

Reputation: 1293

There are two problems here:

  1. 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();
      }
    }
    
  2. 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

David_2002
David_2002

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

Related Questions