</> Michael Burrows

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

Last modified on September 7th 2020 GitHub [Source] CodePen [Demo]

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

Animated text being typed

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

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>

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; }

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; } }

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>

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(); });

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; } }