Welcome to a sharing and tutorial on how to create a typewriter effect with pure Javascript. Want to add some visual eye candy to your website headlines? A typewriter effect will surely catch some attention, and it is actually not that difficult. Read on!
ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.
TABLE OF CONTENTS
DOWNLOAD & DEMO
Firstly, here is the download link to the example code as promised.
QUICK NOTES
If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.
EXAMPLE CODE DOWNLOAD
Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
HOW TO USE & DEMO
<!-- (A) TYPEWRITER CSS + JS -->
<link rel="stylesheet" href="typewriter.css">
<script src="typewriter.js"></script>
<!-- (B) CONTAINER -->
<div id="demo"></div>
<!-- (C) ATTACH TYPEWRITER -->
<script>
tw({
// (C1) REQUIRED
target : document.getElementById("demo"), // target html container
//text : "Wow. Much text. Very paragraph. Such contents.", // text
text : [
"Wow. Much text. Very paragraph. Such contents.",
"Foo! It works!",
"Another random paragraph here."
],
// (C2) OPTIONAL
forward : 80, // delay between each character, default 100 ms
backward : 40, // delay between each character, default 50 ms
pause : 1500, // pause before next cycle, default 1 sec
loop : true, // loop typewriter effect, default true
cursor : true // add fake cursor? default true
});
</script>
For you guys who just want to use this as a “plugin”:
- Load the CSS and JS. Captain Obvious at your service.
- Create an empty HTML container to generate the typewriter text.
- Use
tw()
to attach the typewriter “widget”.target
Required. HTML container to generate the typewriter text in.text
Required. A string of text, or array of strings.forward
Optional. Delay between each character for the forward cycle.backward
Optional. Delay between each character for the backward cycle.pause
Optional. Delay before the next forward/backward cycle.loop
Optional. Loop the text after completion?cursor
Optional. Add a fake blinking cursor?
HOW THE TYPEWRITER EFFECT WORKS
All right, let us now get into the details on how the typewriter effect works – This is for you guys who want to “deep customize” it.
1) TYPEWRITER INITIALIZE
function tw (instance) {
// (A) SET DEFAULT OPTIONS
if (instance.forward === undefined) { instance.forward = 100; }
if (instance.backward === undefined) { instance.backward = 50; }
if (instance.pause === undefined) { instance.pause = 1000; }
if (instance.loop === undefined) { instance.loop = true; }
if (instance.cursor === undefined) { instance.cursor = true; }
if (typeof instance.text != "object") { instance.text = [instance.text]; }
// (B) PROPERTIES & FLAGS
instance.current = 0; // current text
instance.pointer = 0; // current character
instance.direction = true; // true forward, false backward
instance.draw = true; // continue to "type text"
// ...
}
You already know this one, we use function tw()
to attach the typewriter effect. Yes, everything is contained within this single function.
- (A) As in the demo above, we are just dealing with the default settings here.
- (B) Necessary flags to keep track of the animation and progress.
instance.current
– A “pointer” to keep track of the current block of text ininstance.text
.instance.pointer
– Another “pointer” to track the current text character.instance.direction
– Iftrue
, we are “typing out” the text in a forward manner. Iffalse
, we are “deleting” the text in a backward manner.instance.draw
– Has more text to output?
2) TYPEWRITER EFFECT
// (C) TYPEWRITER EFFECT
if (instance.cursor) { instance.target.classList.add("cursor"); }
instance.typist = () => {
// (C1) NEXT CHARACTER
if (instance.direction) {
instance.pointer++;
instance.draw = instance.pointer <= instance.text[instance.current].length;
} else {
instance.pointer--;
instance.draw = instance.pointer >= 0;
}
// (C2) DRAW HTML
if (instance.draw) {
instance.target.innerHTML = instance.text[instance.current].substring(0, instance.pointer);
}
// (C3) PAUSE & LOOP?
else {
// (C3-1) CLEAR TIMER + REVERSE DIRECTION
clearInterval(instance.timer);
instance.direction = !instance.direction;
// (C3-2) NEXT BLOCK OF TEXT
if (instance.direction) {
instance.current++;
if (instance.loop && instance.current == instance.text.length) {
instance.current = 0;
}
if (instance.current <= instance.text.length) {
instance.timer = setTimeout(() => {
instance.timer = setInterval(instance.typist, instance.forward);
}, instance.pause);
}
// (C3-3) PAUSE THEN CLEAR TEXT
else {
instance.timer = setTimeout(() => {
instance.timer = setInterval(instance.typist, instance.backward);
}, instance.pause);
}
}
};
This seems complicated, but it is actually very straightforward. To keep the long story short, instance.typist()
is the function that drives the typewriter effect.
- We put
instance.typist
on an interval timer to output (and remove) the characters one by one. - In the forward cycle (
instance.direction == true
), we doinstance.pointer++
and output the characters one by one until it is complete. - The backward cycle (
instance.direction == false
) then follows. We doinstance.pointer--
until the text is completely removed. - Finally, we proceed with the next block of text
instance.current++
.
3) BLINKING CURSOR EFFECT
@keyframes blink {
0% { opacity: 0; }
100% { opacity: 1; }
}
.cursor::after {
content: "|";
font-size: 1.5em;
font-weight: bold;
animation: blink infinite alternate 0.4s;
}
Look no further, this is just some simple CSS animation to create the “fake cursor”. Very simply, we are just alternating between opacity: 0
and opacity: 1
and a |
character.
EXTRA BITS & LINKS
That’s all for the short project, here are some links that may be useful to you.
LINKS
Need more text effects? Check out my other tutorials:
- Horizontal and Vertical News Ticker – Code Boxx
- Responsive Text Slider – Code Boxx
- Example On CodePen – JS Typewriter
COMPATIBILITY CHECKS
- Arrow Functions – CanIUse
- CSS Animations – CanIUse
This Javascript typewriter effect will work on all modern browsers.
THE END
Thank you for reading, and we have come to the end of this guide. I hope that it has helped you to create more visually appealing elements in your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!
Awesome! By adding one of those cute retro monospace fonts, green colour and black background, and hey presto, it’s 1982 again!
Thanks for the script, it comes in very handily!