Scroll · 21 of 34

Typewriter

Text types itself out one character at a time with a blinking cursor, triggered when it scrolls into view. A small JavaScript loop; the cursor is a CSS blink.

HTML · CSS · JavaScript · No dependencies · MIT

HTML

<section class="typewriter-section">
  <h2 class="typewriter-text"><span class="tw-chars"></span><span class="tw-cursor">|</span></h2>
</section>

CSS

.typewriter-section {
  min-height: 35vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

.typewriter-text {
  font-size: 2.5rem;
  color: #f0f0f5;
}

.tw-cursor {
  display: inline-block;
  margin-left: 2px;
  animation: blink 0.8s step-end infinite;
}

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

JavaScript

var section = document.querySelector('.typewriter-section');
var target = document.querySelector('.tw-chars');
var TEXT = 'Typewriter Reveal';
var SPEED = 80; // ms per character

var interval = null;

function start() {
  stop();
  target.textContent = '';
  var i = 0;
  interval = setInterval(function () {
    if (i < TEXT.length) {
      target.textContent += TEXT[i];
      i++;
    } else {
      stop();
    }
  }, SPEED);
}

function stop() {
  clearInterval(interval);
  interval = null;
}

new IntersectionObserver(function (entries) {
  entries.forEach(function (entry) {
    if (entry.isIntersecting) {
      start();
    } else {
      stop();
      target.textContent = ''; // reset so it replays next time
    }
  });
}, { threshold: 0.25 }).observe(section);