Erik Erik - 7 months ago 39
Javascript Question

typing animated text

I have DIV tag with text inside. Is it possible to change the text content in a loop with a typing effect, where it types out, then goes backward deleting the letters and starting all over with a new text? Is this possible with jquery?


Just a simple approach:

var $typer = $('.typer'),
    txt = $"text"),
    tot = txt.length,
    ch  = 0;

(function typeIt() {   
  if(ch > tot) return;
  $typer.text( txt.substring(0, ch++) );
  setTimeout(typeIt, ~~(Math.random()*(300-60+1)+60));
.typer:after {
  display: inline-block;
  vertical-align: middle;
  background: #000;
  animation: caretPulsate 1s linear infinite; 
  -webkit-animation: caretPulsate 1s linear infinite; 
@keyframes caretPulsate {
  0%   {opacity:1;}
  50%  {opacity:1;}
  60%  {opacity:0;}
  100% {opacity:0;}
@-webkit-keyframes caretPulsate {
  0%   {opacity:1;}
  50%  {opacity:1;}
  60%  {opacity:0;}
  100% {opacity:0;}
<script src=""></script>
<span class="typer" data-text="Hi! My name is Al. I will guide you trough the Setup process."></span>

So basically jQuery gets the data-text of your element, inserts character by character, and the pulsating "caret" is nothing by a CSS3 animated :after element of that SPAN.

See also: Generate random number between two numbers in JavaScript