[JavaScript] Type Text Effect


Demo





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

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 = 80;

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 PlayParallel() {
  var spans = document.querySelectorAll("span[data-typedtext]");
  for (var i = 0; i < spans.length; ++i) {
    var span = spans[i];
    Playing([span], 0, 0);
  }
}

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

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]
[2]18 of the Best Personal Websites We've Ever Seen
[3]STRML: Projects and Work
[4]
[5]
[6]
[7]
[8][JavaScript] Typing Text Effect