Writing effect in Javascript

Asked

Viewed 110 times

3

I have a writing effect code, but it only works when updating the page, I wanted it to run automatically, someone can give a strength?

Below is the code. what I need to change or add to make it infinite, without having to update the page?

 function typeWriter(elemento) {
    const textoArray = elemento.innerHTML.split('');
    elemento.innerHTML = '';
    textoArray.forEach((letra, i) => {
      setTimeout(() => elemento.innerHTML += letra, 75 * i);
    });
  }
  const titulo = document.querySelector('h1');
  typeWriter(titulo);

Note: the writing is coming from a h1 I put into HTML.

1 answer

3

Add another setTimeout calling the same function when the forEach reach the last letter of the text. The time of this interval you sum with the 75 * i. For example, if you want to repeat the effect after 1 second it has finished:

75 * i + 1000

Will stay like this:

function typeWriter(elemento) {
   const textoArray = elemento.innerHTML.split('');
   elemento.innerHTML = '';
   textoArray.forEach((letra, i) => {
      setTimeout(() => elemento.innerHTML += letra, 75 * i);
      if(textoArray.length-1 == i){
         setTimeout(() => typeWriter(elemento), 75 * i + 1000);
      }
   });
}

const titulo = document.querySelector('h1');
typeWriter(titulo);
<h1>teste de escrita</h1>

Adding a bar at the end

Place the bar | at the end of the text and change the script using .pop() to remove the array bar and the way to change innerHTML:

function typeWriter(elemento) {
   const textoArray = elemento.innerHTML.split('');
   textoArray.pop();
   elemento.innerHTML = '';
   textoArray.forEach((letra, i) => {
      setTimeout(() => elemento.innerHTML = elemento.innerHTML.replace("|", "") + letra +"|", 75 * i);
      if(textoArray.length-1 == i){
         setTimeout(() => typeWriter(elemento), 75 * i + 1000);
      }
   });
}

const titulo = document.querySelector('h1');
typeWriter(titulo);
<h1>teste de escrita|</h1>

  • thanks a lot. it worked! , just out of curiosity, as I do to put that bar ?

  • I added it in the reply. See if it solves.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.