Typewriter Effect Javascript
Shared by: devcanvas
javascript
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Let’s break down the code step by step:
-
Function Parameters:
elementId
: The ID of the HTML element where the text will be displayed.text
: The string of text to animate.speed
: The typing speed in milliseconds (default is 100ms per character).
-
Get the Element: The
document.getElementById(elementId)
function retrieves the HTML element by its ID so the function knows where to display the animated text. -
Character-by-Character Typing:
- The
type()
function is a recursive function that appends one character from thetext
string to the element’s content each time it is called. - The
index
variable tracks which character should be typed next.
- The
-
Timing:
setTimeout(type, speed)
ensures thetype()
function runs repeatedly with a delay determined by thespeed
parameter.- This creates the typing effect at the desired pace.
-
Stopping the Typing: Once
index
equals the length of thetext
string, the typing stops as theif
condition prevents further recursion.
HTML Example
To use this snippet, you need an HTML element to act as the target for the animation:
<div id="typewriter"></div>
Then, simply call the function in a <script>
tag or your JavaScript file:
typewriterEffect("typewriter", "Welcome to my website!", 150);
Customizing the Typewriter Effect
This snippet is highly customizable to fit your project’s needs:
1. Add a Blinking Cursor:
Make the effect more realistic by adding a blinking cursor with CSS:
<style>
#typewriter {
display: inline;
border-right: 2px solid black;
white-space: nowrap;
overflow: hidden;
}
@keyframes blink {
50% {
border-color: transparent;
}
}
#typewriter {
animation: blink 0.5s step-end infinite;
}
</style>
2. Add a Typing Delay:
You can modify the function to include pauses at specific points in the text, such as after punctuation:
function typewriterEffectWithPause(elementId, text, speed = 100, delay = 500) {
const element = document.getElementById(elementId);
let index = 0;
function type() {
if (index < text.length) {
element.textContent += text.charAt(index);
index++;
const char = text.charAt(index - 1);
const extraDelay = [".", ",", "!", "?"].includes(char) ? delay : 0;
setTimeout(type, speed + extraDelay);
}
}
type();
}
// Usage:
typewriterEffectWithPause("typewriter", "Hello, World! This is a typewriter effect!", 100, 500);
Tags
- “Typewriter effect JavaScript”
- “Text animation for websites”
- “Dynamic text effect tutorial”
- “Custom typewriter animation”
- “Typing effect code example”