In order to get this effect, we’ll need a good understanding of javascript. This will be dynamic so it doesn’t matter how many words we have, or the length of them, it’ll work anyways.

In this case, the effect will be done only by the javascript to a specific element. With that being said, this will be the minimum HTML needed:

<span id="text"></span>

The rest of the code would be javascript, and to make things easier let’s split the algorithm into two processes, type and erase. Will be typing a word with a function but after that, it’ll call the function to erase it and so on.

Besides the functions, let’s keep in mind that we also need a list of words, the position of the character, the position of the word and the speed of typing and erasing.

After this pre-talk, this is all the javascript will need

var wordList = ['python', 'javascript', 'laravel', 'wordpress'];
var characterPosition = 0, wordPosition = 0;
var typeSpeed = 200, eraseSpeed = typeSpeed/2;
function typeWord() {
  if (characterPosition < wordList[wordPosition].length) {
    document.getElementById("text").innerHTML += wordList[wordPosition].charAt(characterPosition)
    characterPosition++
    setTimeout(typeWord, typeSpeed)
  } else {
  	setTimeout(eraseWord, eraseSpeed)
  }
}
function eraseWord() {
	if (characterPosition >= 0) {
      var word = wordList[wordPosition].toString().substring(0, characterPosition)
      document.getElementById("text").innerHTML = word
      characterPosition--
      setTimeout(eraseWord, eraseSpeed)
  } else {
    wordPosition++;
    if (wordPosition >= wordList.length) wordPosition = 0
    setTimeout(typeWord, typeSpeed)
  }
}

And then just call the function

setTimeout(typeWord, typeSpeed)

Basically everything it’s just about two for loops that iterate the list of word and the list of characters. This is how it works:

  • First, it goes to the first word
  • Second, it goes to the first character of the first word
  • Third, it sets the character to the HTML element
  • This process will be in a loop until it reaches the final position of the word, then it will call the erase function that it’s basically the same but backward.
  • Then, it takes the next word.
  • Finally, it starts over again.
Typing effect with minimum needed code

At this point, you can add more elements among the element javascript is using to get a better integration.

<h1 class="text">
 <span>Learning</span>
 <span id="text"></span>
 <span class="text__decorator">_</span>
</h1>

And we get this:

Typing effect with contextual elements

More than that is just styling, here you have the full codepen project to play with it.

See the Pen Typing effect by Dager (@dagerzuga) on CodePen.dark