Introduction
In this lab, we will learn how to create a typewriter effect animation using HTML, CSS, and JavaScript. The typewriter effect is a popular animation that simulates the appearance of text being typed on a page, one character at a time. By the end of this lab, you will be able to create your own typewriter effect animation to add a dynamic and engaging element to your web projects.
Typewriter Effect
index.html and style.css have already been provided in the VM.
To create a typewriter effect animation, follow these steps:
- Define two animations,
typingandblink.typinganimates the characters, andblinkanimates the caret. - Use the
::afterpseudo-element to add the caret to the container element. - Use JavaScript to set the text for the inner element and set the
--charactersvariable, which contains the character count. This variable is used to animate the text. - Use
white-space: nowrapandoverflow: hiddento make content invisible as necessary.
Here's the HTML code:
<div class="typewriter-effect">
<div class="text" id="typewriter-text"></div>
</div>
And here's the CSS code:
.typewriter-effect {
display: flex;
justify-content: center;
font-family: monospace;
}
.typewriter-effect > .text {
max-width: 0;
animation: typing 3s steps(var(--characters)) infinite;
white-space: nowrap;
overflow: hidden;
}
.typewriter-effect::after {
content: " |";
animation: blink 1s infinite;
animation-timing-function: step-end;
}
@keyframes typing {
75%,
100% {
max-width: calc(var(--characters) * 1ch);
}
}
@keyframes blink {
0%,
75%,
100% {
opacity: 1;
}
25% {
opacity: 0;
}
}
And finally, here's the JavaScript code:
const typeWriter = document.getElementById("typewriter-text");
const text = "Lorem ipsum dolor sit amet.";
typeWriter.innerHTML = text;
typeWriter.style.setProperty("--characters", text.length);
Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.
Summary
Congratulations! You have completed the Typewriter Effect lab. You can practice more labs in LabEx to improve your skills.