DEV Community

Michael Burrows
Michael Burrows

Posted on • Edited on • Originally published at w3collective.com

Create an animated typing text effect (CSS & JS solutions)

This article outlines two different solutions to achieve an animated (typewriter) text effect.

Alt Text

A simple pure CSS solution and a more elaborate solution using JavaScript.

Working demo of each solution can be found here -> https://codepen.io/michaelburrows/pen/QWyBpGN

CSS Solution

Let’s get started by adding the text we want to animate to the HTML.

<div id="type-css">
  <h1>Lorem ipsum dolor sit consectetur.</h1>
</div>
Enter fullscreen mode Exit fullscreen mode

Next the CSS.

#type-css {
  position: absolute;
}
#type-css h1 {
  overflow: hidden;
  line-height: 1;
  white-space: nowrap;
  border-right: 3px solid #fff;
  animation: type 3.5s steps(35, end), cursor 1s step-end infinite;
}
Enter fullscreen mode Exit fullscreen mode

Finally the CSS for the animation that gives the appearance of text being typed and a blinking cursor.

@keyframes type {
  from { width: 0; }
  to { width: 100%; }
}
@keyframes cursor {
  from, to { border-color: transparent; }
  50% { border-color: #fff; }
}
Enter fullscreen mode Exit fullscreen mode

JavaScript Solution

While the CSS solution looks good Javascript allows us to create an even more realistic typing effect.

To start insert a h1 or any other tag you want to use into the HTML.

<h1 id="type-js"></h1> 
Enter fullscreen mode Exit fullscreen mode

Next for the Javascript.

This script outputs each of letters, one at a time, at a random interval.

Simply replace the const text with the text you would like to animate.

document.addEventListener("DOMContentLoaded", function () {
  let letter = 0;
  const text = "Lorem ipsum dolor sit consectetur.";
  function typeText() {
    if (letter < text.length) {
      document.getElementById("type-js").innerHTML += text.charAt(letter);
      letter++;
      let speed = Math.floor(Math.random() * 150) + 50;
      setTimeout(typeText, speed);
    }
  }
  typeText();
});
Enter fullscreen mode Exit fullscreen mode

As the JavaScript handles the text animation we only need the CSS animation for the blinking cursor.

#type-js {  
  display: inline-block;
  line-height: 1;
  border-right: 3px solid #fff;  
  animation: cursor 1s step-end infinite;
}
@keyframes cursor {
  from, to { border-color: transparent; }
  50% { border-color: #fff; }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)