If you’ve seen any modern thriller or military-themed films, you’re familiar with text print-outs, which are frequently used to present a new scene or location in the movie. While they are intended to portray high-tech communication, these teletype effects derive from technology nearly 200 years old; today, it’s our goal to recreate them using web technologies. Most of the available scripts to do so are written in JQuery, which really isn’t needed in today’s browsers; instead, I’ll demonstrate a technique using plain JavaScript.

Plaintext Start

In most cases, a monospaced font will work best with this effect. The text is placed inside an appropriate tag:

<pre id="teletype" hidden>Somewhere in the South Pacific</pre>

teletype has a hidden attribute, preventing it from being seen. A millisecond or two after it is presented in a hidden state on the page, the text string is picked up by our JavaScript and cloned, after defining a cursor element:

let cursor = "<span>|</span>",
telecopy = teletype.innerHTML;

The text is printed out with a function:

function typeIt() {
  let counter = 0;
  teletype.innerHTML = cursor;
  teletype.removeAttribute("hidden");
  let i = setInterval(function(){
    teletype.innerHTML = telecopy.substr(0, counter) + cursor;
      counter++;
      if(counter === telecopy.length + 1) {
          clearInterval(i);
      }
  }, 100);
}

typeIt();

The typeIt function sets a counter variable to 0, and the innerHTML of the on-screen element to the cursor before exposing the altered element to the user.

Then, the JavaScript loops through the telecopy function, grabbing an increasing number of letters from it, always concatenating cursor onto the end, with 1/10th of a second (100 milliseconds) between each loop. When the number of loops is equal to the number of characters in the original string, the setInterval exits.

Adding A Cursor Blink

During the typing sequence and continuing once it is complete, the cursor element should be blinking regularly, as if awaiting more input. This is created through a CSS animation:

@keyframes blink {
  from, to {
    color: transparent;
  }
  50% {
    color: black;
  }
}

The animation is called upon with this:

#teletype span {
  animation: blink 1s step-end infinite;
}

I’ve left a more complex version that takes user input at the start of this article, as well as on the associated CodePen. If you want more advanced options, I’d suggest scripts like Matt Boldt’s TypedJS.

Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.
Check out the CodePen demo for this article at https://codepen.io/dudleystorey/pen/WGrWQO