Make another sentence appear in the same place as the previous one, after an animation

Asked

Viewed 43 times

0

The thing is, I need a sentence to appear as if it were typed on the screen, and after the first sentence appears completely, a new one should appear in the same way as the previous one. The part about showing the text has already been done, but I don’t know how to implement the phrase replacement part. Does anyone have any idea how this can be done?

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

const titulo = document.querySelector('.fundo-roxo');
typeWriter(titulo);
<div class="col-xs-12 col-md-12">
  <h1 class="titulo-linha-1"><span class="fundo-roxo">Texto 1.</span></h1>
</div>

1 answer

0

You can solve this with a function called Slice, having two variables one to keep the text and another that will change, and making a loop so that it is possible to treat this variable, so your code would look like something like this:

First it would separate two variables to treat being that the first would be empty and the second with the text that will not be changed.

var textoTratar = '';
var textCompleto = 'Texto 1.';

To write you could pick one letter at a time from this variable and add gradually.

//Escrever
for (var i = 0; i < textCompleto.length; i++) {

    //console.log(i);

    textoTratar += textCompleto.slice(i, i + 1);

    document.getElementById('alpha').innerHTML = textoTratar;

}

And to erase you can do the reverse process by taking the text itself and removing one letter at a time

//Apagar
for (var i = 0; i < textCompleto.length; i++) {

    //console.log(i);

    textoTratar = textoTratar.slice(0, textoTratar.length - 1);

    document.getElementById('alpha').innerHTML = textoTratar;

}

NOTE: I did the loop with a for, but you can use the type of loop that you prefer, because the for will be very fast and won’t be able to see the effect of writing on the screen.

Browser other questions tagged

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