0

How can I use JavaScript/jQuery to get text to appear in succession?

I want a half second between each character, and then I want to repeat the same succession 2-3 times. I am coming up dry on all of my web searches for this.

P̲̳x͓L̳
  • 3,615
  • 3
  • 29
  • 37
  • Possibly a duplicate (but the mention of repetition '2-3 times' gives me pause) of this answer, though the question seems to have been asked badly and then badly edited since: http://stackoverflow.com/questions/13325008/typewriter-effect-with-jquery – David Thomas Mar 31 '14 at 22:29

1 Answers1

2

jsFiddle Demo

Use timeouts with callbacks. You can do this natively with javascript using setTimeout, or with jQuery using delay. In order to facilitate the repetition, you could use a recursive loop with a counter for completion in addition to current text offset.

html for demo

<div id="d"></div>

js for demo

var text = "Hello World!";
var d = $("#d")[0];
(function write(i,n){
 if( i == text.length ){
  if( n == 2 ) return;
  d.innerHTML = "";
  setTimeout(function(){write(0,++n)},500);
 }else{
  d.innerHTML += text[i++];
  setTimeout(function(){write(i,n)},500);
 }
})(0,0)

Here is a slightly more in depth demo which uses a block of text (the writing is sped up for proof of concept). http://jsfiddle.net/64uNd/

Travis J
  • 81,153
  • 41
  • 202
  • 273