#AD 50 Projects In 50 Days (HTML, CSS & JavaScript) - Sharpen your skills by building 50 mini projects!
#css #js

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

By Michael Burrows | Last modified September 7th 2020 | GitHub Source Code [GitHub]

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>
Code language: HTML, XML (xml)

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; }
Code language: CSS (css)

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; } }
Code language: CSS (css)

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>
Code language: HTML, XML (xml)

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(); });
Code language: JavaScript (javascript)

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; } }
Code language: CSS (css)

Related Posts