DEV Community 👩‍💻👨‍💻

Cover image for Typewriter Effect with CSS and JS
Walter Nascimento
Walter Nascimento

Posted on

Typewriter Effect with CSS and JS

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> 
Enter fullscreen mode Exit fullscreen mode

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; }
}
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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)

Classic DEV Post from 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!