Typewriter Script

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.

<script type="text/javascript">
// set up text to print, each item in array is new line
var aText = new Array(
"line 1",
"line 2",
"line 3",
"line 4",
"line 5",
"    ",
"line 7",
"line 8",
"THE END "
);
var iSpeed = 100; // time delay of print out
var iIndex = 0; // start printing array at this posision
var iArrLength = aText[0].length; // the length of the text array
var iScrollAt = 20; // start scrolling up at this many lines
 
var iTextPos = 0; // initialise text position
var sContents = ''; // initialise contents variable
var iRow; // initialise current row
 
function typewriter()
{
 sContents =  ' ';
 iRow = Math.max(0, iIndex-iScrollAt);
 var destination = document.getElementById("typedtext");
 
 while ( iRow < iIndex ) {
  sContents += aText[iRow++] + '<br />';
 }
 destination.innerHTML = sContents + aText[iIndex].substring(0, iTextPos) + "_";
 if ( iTextPos++ == iArrLength ) {
  iTextPos = 0;
  iIndex++;
  if ( iIndex != aText.length ) {
   iArrLength = aText[iIndex].length;
   setTimeout("typewriter()", 500);
  }
 } else {
  setTimeout("typewriter()", iSpeed);
 }
}
</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.

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

 

Comments

Nice - Line 29 you're missing the end of the quotes - sContents += aText[iRow++] + ' ';
Permalink
Yup, I had forgotten to encode the <br /> tag at the end of that line. I've fixed that now.
Name
Philip Norton
Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
7 + 4 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.