Hacker Typer

HTML

<!-- The contents of this element can be replaced with anything. -->
<pre>
Hello World
</pre>

CSS

/* This CSS isn't necessary at all, it just shows a blinking cursor as you type. */

pre::after {
  content: '|';
  /* 1.06s is the default cursor blink rate on Windows. */
  animation: 1.06s steps(1) infinite blink;
}

@keyframes blink {
  50% { opacity: 0 }
}

JavaScript

/**
 * @param {Node} node
 *   A node that will have its content cleared and text revealed gradually.
 * @param {RegExp} tokenizer
 *   A regular expression that defines the boundaries of each token. Must
 *   specify the global flag
 
 * @returns {function}
 *   Reveals one token of the node text each time it's called.
 */
function createTyper(node, tokenizer) {
  if (!tokenizer.global) {
    // If the tokenizer regex is not global it will start match from the
    // beginning of the text each time.
    throw new Error('Tokenizer must specify the global flag');
  }
  
  // Save the text content of the node so we can reveal it gradually.
  const text = node.innerText;
  
  // Hide the initial node content.
  node.innerText = '';
  
  // Return a function that will reveal one token each time it's called.
  return function() {
    const match = tokenizer.exec(text);
    if (match) {
      node.innerText = text.substr(0, match.index + match[0].length);
    }
  };
}

// This tokenizer will match either one word or any sequence of symbols.
const wordOrSymbols = /[a-z0-9]+|[^a-z0-9\s]+/ig;
// Other example tokenizers:
// oneCharacter = /./g
// nonWhitespace = /\S/g
// upToFive = /\w{1,5}/g

// This initialises the typer and will clear the text when called.
// 'type' is now a function that we can call to reveal one token at a time.
let type = createTyper(document.querySelector('pre'), wordOrSymbols);

// Reveal one token each time a key is pressed.
document.addEventListener('keydown', type);