Erik Erik - 5 months ago 32
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?

Answer

Just a simple approach:

var $typer = $('.typer'),
    txt = $typer.data("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));
}());
/* PULSATING CARET */
.typer:after {
  content:"";
  display: inline-block;
  vertical-align: middle;
  width:1px;
  height:1em;
  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="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></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