Text that is typed in the Few?

10

People, I see an effect on the sites. The text will appear (as if someone was typing it). Automatically I related to the marquee, but the effect is not legal. Do you know how to do it?

    
asked by anonymous 14.05.2015 / 22:37

4 answers

19

This is +/- simple. An example would look like this:

var div = document.getElementById('log');
var texto = 'Hoje está um lindo dia!';

function escrever(str, el) {
  var char = str.split('').reverse();
  var typer = setInterval(function() {
    if (!char.length) return clearInterval(typer);
    var next = char.pop();
    el.innerHTML += next;
  }, 100);
}

escrever(texto, div);
<div id="log"></div>

From a text string it breaks the string into an array, character by character and inverts the order (to be able to use .pop ).

Then using setInterval and .pop() vams emptying this array with text.

jsFiddle: link

    
14.05.2015 / 22:45
5

Alternative:

var texto = "Hello World!!!";
var result;

var count = 0;
function digitar() {
  result = document.getElementById("result");
  window.setTimeout(function() { inserir(texto[count]) }, 200);
}

function inserir(letra) {
  result.innerHTML += letra;
  count++;
  if(count < texto.length)
    window.setTimeout(function() { inserir(texto[count]) }, 200);
}

window.onload = digitar;
<div id="result"></div>
    
14.05.2015 / 22:59
5

Alternative to colleague's code [Sergio], just to put everything in a function, without having global variables (which will hardly be used by other functions)

function typeWritter(texto,idElemento,tempo){
    var char = texto.split('').reverse();
    var typer = setInterval(function () {
        if (!char.length) return clearInterval(typer);
        var next = char.pop();
        document.getElementById(idElemento).innerHTML += next;
    }, tempo);
}
typeWritter('Hoje está um lindo dia!','log',100);

function typeWritter(texto,idElemento,tempo){
    var char = texto.split('').reverse();
    var typer = setInterval(function () {
        if (!char.length) return clearInterval(typer);
        var next = char.pop();
        document.getElementById(idElemento).innerHTML += next;
    }, tempo);
}
typeWritter('Hoje está um lindo dia!','log',100);
<div id="log"></div>

JsFiddle link

    
30.09.2016 / 07:21
2

An alternative to the [Sergio] code using an anonymous function:

(function() {
  var node = document.getElementById('message'),
    message = "This is my message... ! Thx =)",
    current = message.split("").reverse(),
    interval = setInterval(function() {
      if (current.length)
        node.innerHTML += current.pop();
      else
        clearInterval(interval);
    }, 300);
}());
<div id="message"></div>
    
03.02.2017 / 04:37