Welcome to a quick tutorial on how to create a typewriter effect with Javascript. So you want to add some eye-catching headlines to your website? A very simple typewriter effect can be achieved with:
<!-- (A) EMPTY HTML DIV -->
<div id="demo"></div>
<script>
// (B) TEXT TO WRITE & CURRENT CHARACTER
var txt = "TEXT", char = 0;
// (C) FUNCTION TO "TYPE" THE TEXT IN INTERVAL
var timer = setInterval(() => {
char++;
document.getElementById("demo").innerHTML = txt.substring(0, char);
if (char == txt.length) { clearInterval(timer); }
}, 500);
</script>
That covers the quick basics, but how about repeating the text? Rotating between different blocks of texts? A backward typewriter effect to clear the text? Adding a fake cursor? I have written an entire plugin so you don’t have to – Read on!
TABLE OF CONTENTS
DOWNLOAD & DEMO
Here is the download link to the example code, so you don’t have to copy-paste everything.
EXAMPLE CODE DOWNLOAD
Source code on GitHub Gist | Example on CodePen
Just click on “download zip” or do a git clone. 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 -->
<!-- class="retro|impact|rose|code|banana" -->
<div id="demo"></div>
<!-- (C) ATTACH TYPEWRITER -->
<script>
tw({
// (C1) REQUIRED
target : document.getElementById("demo"),
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 block of text, default 1 sec
loop : true, // loop text blocks, default true
cursor : true // add fake cursor, default true
});
</script>
Theme:
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
<div>
for the typewriter text. I have also included some “simple themes”, just addclass="THEME"
to the<div>
… Or feel free to set your own. - Use
tw()
to attach the typewriter.target
Required. HTML container to generate the typewriter text in.text
Required. A string, 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 block of text.loop
Optional. Loop the text after completion?cursor
Optional. Add a fake blinking cursor?
SORRY FOR THE ADS...
But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.
Buy Me A Coffee Code Boxx eBooks
JAVASCRIPT TYPEWRITER EFFECT
All right, let us now get into more details on how the typewriter effect works – This is for you guys who want to “deep customize” it.
TUTORIAL VIDEO
PART 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 block of text
instance.char = 0; // current character
instance.direction = true; // true forward, false backward
instance.draw = true; // continue to "type text"
// (C) ATTACH FAKE CURSOR
if (instance.cursor) { instance.target.classList.add("cursor"); }
}
- (A) As you already know, we pass in a settings object when calling
tw()
. If a setting is not defined, we will use these default values. - (B) Flags to keep track of the animation and progress.
instance.current
– To keep track of the current block of text ininstance.text
.instance.char
– 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?
- (C) Create the fake cursor. Yes, it’s just a simple
.cursor
CSS class.
PART 2) TYPEWRITER EFFECT
// (D) TYPEWRITER EFFECT
instance.typist = () => {
// (D1) NEXT CHARACTER
if (instance.direction) {
instance.char++;
instance.draw = instance.char <= instance.text[instance.current].length;
} else {
instance.char--;
instance.draw = instance.char>= 0;
}
// (D2) DRAW HTML
if (instance.draw) {
instance.target.innerHTML = instance.char==0 ? " " : instance.text[instance.current].substring(0, instance.char);
}
// (D3) PAUSE & LOOP?
else {
// (D3-1) CLEAR TIMER + REVERSE DIRECTION
clearInterval(instance.timer);
instance.direction = !instance.direction;
// (D3-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);
}
}
// (D3-3) PAUSE THEN CLEAR TEXT
else {
instance.timer = setTimeout(() => {
instance.timer = setInterval(instance.typist, instance.backward);
}, instance.pause);
}
}
};
// (E) START
instance.timer = setInterval(instance.typist, instance.forward);
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.
- (E) As in the introduction, we put
instance.typist
in an interval timerinstance.timer
to output and remove the characters one by one. - (D1 & D2) In the forward cycle (
instance.direction == true
), we doinstance.char++
and output the characters one by one until it is complete. - (D3-1 & D3-3) When the current block of text is fully output, we reverse to remove the characters –
instance.direction == false
- (D1) The backward cycle does
instance.char--
until the text is completely removed. - (D3-1 & D3-2) Finally, proceed with the next block of text
instance.current++
.
PART 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.
EXTRAS
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
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!