Using JavaScript and CSS let's create a typewriter effect
Code
HTML
First let's create the interface, we'll do something simple, using just HTML.
<h1 id="elementEl">Walter Nascimento Barroso</h1>
Let's just add an h1 with an id elementEl, so it's easier to identify in both css and javascript
CSS
#elementEl::after {
content: '|';
margin-left: 5px;
animation: blink 0.7s infinite;
}
@keyframes blink {
0% { opacity: 1; }
100% { opacity: 0; }
}
In css we take elementEl and add a slash after our h1 and finally we add the blink effect so the added slash will be blinking
JS
'use strict';
function typeWriter(el) {
const textArray = el.innerHTML.split('');
el.innerHTML = '';
textArray.forEach((letter, i) =>
setTimeout(() => (el.innerHTML += letter), 95 * i)
);
setInterval(() => typeWriter(el), 8000);
}
typeWriter(elementEl);
Here in our javascript we just have a function called typeWriter, which receives our elementEl.
Inside our function we have a constant that divides the text of our element letter by letter, then we clear the element content and loop through our array of letters and for each letter we add we wait for the time of 95 multiplied by the index and so we have a letter at a time added
Finally, we call setInterval again to call our typeWrite function again.
ready simple like that.
Demo
See below for the complete working project.
if you can't see it click here and see the final result
Youtube
If you prefer to watch it, see the development on youtube.
Thanks for reading!
If you have any questions, complaints or tips, you can leave them here in the comments. I will be happy to answer!
ππ See you later! ππ
Support Me
Youtube - WalterNascimentoBarroso
Github - WalterNascimentoBarroso
Codepen - WalterNascimentoBarroso
Top comments (0)