Typewriter Script

3rd February 2009

The following script can be used if you want to simulate a typewriter in an element on screen. I have put in a lot of comments to describe what is happening but the script works by taking each array element in turn and adding it character by character to the content of the selected element.

  1. <script type="text/javascript">
  2. // set up text to print, each item in array is new line
  3. var aText = new Array(
  4. "line 1",
  5. "line 2",
  6. "line 3",
  7. "line 4",
  8. "line 5",
  9. " ",
  10. "line 7",
  11. "line 8",
  12. "THE END "
  13. );
  14. var iSpeed = 100; // time delay of print out
  15. var iIndex = 0; // start printing array at this posision
  16. var iArrLength = aText[0].length; // the length of the text array
  17. var iScrollAt = 20; // start scrolling up at this many lines
  18.  
  19. var iTextPos = 0; // initialise text position
  20. var sContents = ''; // initialise contents variable
  21. var iRow; // initialise current row
  22.  
  23. function typewriter()
  24. {
  25. sContents = ' ';
  26. iRow = Math.max(0, iIndex-iScrollAt);
  27. var destination = document.getElementById("typedtext");
  28.  
  29. while ( iRow < iIndex ) {
  30. sContents += aText[iRow++] + '<br />';
  31. }
  32. destination.innerHTML = sContents + aText[iIndex].substring(0, iTextPos) + "_";
  33. if ( iTextPos++ == iArrLength ) {
  34. iTextPos = 0;
  35. iIndex++;
  36. if ( iIndex != aText.length ) {
  37. iArrLength = aText[iIndex].length;
  38. setTimeout("typewriter()", 500);
  39. }
  40. } else {
  41. setTimeout("typewriter()", iSpeed);
  42. }
  43. }
  44. </script>

You can run this script by either including an onload attribute in the body tag, or by placing a call to the typewriter() function after the element that you want to use to fill the text with.

  1. <div id="typedtext"></div>
  2. <script type="text/javascript">typewriter();</script>

 

Comments

Permalink
Nice - Line 29 you're missing the end of the quotes - sContents += aText[iRow++] + ' ';

Jamie Bicknell (Tue, 02/03/2009 - 18:26)

Permalink
Yup, I had forgotten to encode the
tag at the end of that line. I've fixed that now.

philipnorton42 (Tue, 02/03/2009 - 19:12)

Add new comment

The content of this field is kept private and will not be shown publicly.