typing animated text

A simple approach:

const elsTyper = document.querySelectorAll("[data-typer]");
const rand = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);

const typer = (el) => {
  const text = el.dataset.typer;
  const tot = text.length;
  let ch = 0;

  (function typeIt() {
    if (ch > tot) return;
    el.textContent = text.substring(0, ch++);
    setTimeout(typeIt, rand(60, 300));
  }());
};

elsTyper.forEach(typer);
/* PULSATING CARET */
[data-typer]:after {
  content:"";
  display: inline-block;
  vertical-align: middle;
  width:1px;
  height:1em;
  background: #000;
  animation: caretPulsate 1s linear infinite; 
}
@keyframes caretPulsate {
  0%   {opacity:1;}
  50%  {opacity:1;}
  60%  {opacity:0;}
  100% {opacity:0;}
}
<span data-typer="Hi! My name is Al. I will guide you trough the Setup process."></span>
<h3 data-typer="This is another typing animated text"></h3>

So basically get the data-typer string of your element, insert character by character using a random min-max timeout. The pulsating “caret” is nothing by a CSS3 animated :after pseudo element of that same SPAN.

See also: Generate random number between two numbers in JavaScript

Leave a Comment