[JavaScript] Typing Text Effect


Demo





The three lines in demo are being typed sequentially. If you want the three lines being typed parallel, see my another post [1].

Source Code

HTML: Put the texts to be typed in data-typedtext attribute of span element.

<span data-typedtext="May I be happy. May I be free from stress & pain. May I be free from animosity. May I be free from oppression. May I be free from trouble. May I look after myself with ease."></span>
<span data-typedtext="願我得喜樂。願我離憂苦。願我不受敵意。願我不受壓迫。願我免遭困難。願我輕鬆照顧自己。"></span>
<span data-typedtext="ขอให้ข้าพเจ้าจงเป็นผู้ถึงสุข จงเป็นผู้ไร้ทุกข์ จงเป็นผู้ไม่มีเวร จงเป็นผู้ไม่เบียดเบียนซึ่งกันและกัน จงเป็นผู้ไม่มีทุกข์ จงรักษาตนอยู่เป็นสุขเถิด"></span>

JavaScript:

'use strict';

var speed = 15;

function Playing(elements, elementIndex, textIndex) {
  if (elementIndex == elements.length) {
    return;
  }
  var element = elements[elementIndex];
  if (textIndex == element.dataset.typedtext.length) {
    setTimeout(Playing, speed, elements, elementIndex + 1, 0);
  } else {
    element.textContent += element.dataset.typedtext[textIndex];
    setTimeout(Playing, speed, elements, elementIndex, textIndex + 1);
  }
}

function PlaySequential() {
  var spans = document.querySelectorAll("span[data-typedtext]");
  Playing(spans, 0, 0);
}

document.addEventListener("DOMContentLoaded", function(event) {
  PlaySequential();
});

The key point in the above code is that the Playing function calls itself repeatedly by setTimeout, and in each function call, only one character or letter is appended to the textContent of the element.


Tested on: Chromium Version 56.0.2924.76 Built on Ubuntu , running on Ubuntu 16.10 (64-bit)


References:

[1][JavaScript] Type Text Effect
[2]