typewriter effect

by CBroe

HTML

<pre><b>If</b> implemented correctly,
this <a href="#">type-writer</a> effect
should look <strong>quite nice</strong>.</pre>

CSS

pre { font-size:2.5em; font-family:'lucida console'; }
pre > span { display:inline-block; background:#eee; animation-name:tw; animation-duration:var(--duration); animation-timing-function:steps(var(--steps), jump-start); animation-delay:var(--delay); animation-fill-mode: forwards; clip-path: polygon(0% 0%,00% 0%,00% 100%,0% 100%); }

@keyframes tw {
  from {
    clip-path: polygon(0% 0%,00% 0%,00% 100%,0% 100%);
  }
  to {
    clip-path: polygon(0% 0%,100% 0%,100% 100%,0% 100%);
  }
}

/* polygon(0% 0%,80% 0%,80% 100%,0% 100%) */

JavaScript

let pre = document.querySelector('pre'),
	lines = pre.innerHTML.split(/\n/g),
  factor = 16, /* 1/s */
  delay = 0;
pre.innerHTML = '<span>' + lines.join('</span>\n<span>') + '</span>';
pre.parentNode.querySelectorAll('pre > span').forEach(function(e, i) {
  let chars = e.innerText.length;
  e.style.setProperty('--steps', chars);
  e.style.setProperty('--duration', chars / factor + 's');
  e.style.setProperty('--delay', delay + 's');
  delay += chars / factor;
});
console.log(pre.innerHTML)