How to make typing effect

Request demo

We will achive the typing effect with the help of vanilla javascript.

This code will help you to fire the effect when the page loads without any use of buttons.

Fist of all select your element with js.


  window.onload = () => {
    const elem = document.querySelector("#box");
  }
        

Covering it in window.onload so that we wont get any error. Otherwise the elem's value could be null.

Now make a variable to store your string which you want to be typed.


  const str = "Hello everyone I want this text to be typed out =)";
        

Now we will iterate through the str variable i.e. we will loop through each character of the string to type each character.

Start a for loop (or while loop which you favour but here we will use for loop).


  window.onload = () => {
    • • •
    for (let i = 0; i < str.length; i++) {
      let character = str.charAt(i);
    }
  }
        

Here str.charAt(i) will give us the charcter present in the ith position. So in every iteration we will get each character one by one.

Now we will finally write the string into the box.


  window.onload = () => {
    • • •
      let character = str.charAt(i);
      elem.textContent += character;
    }
  }
        

We are almost done. Till now you will get the text written instantly and wont get any animation. For getting the anination you need to add a delay.

For adding a delay we will use Promises and async await for adding a delay.

Now we will define a function to add a delay. Make sure to intitialise the function before window.onload function as we are using arrow function. This way to use promises is inspired by Mike Sir.


  // Taking milli seconds as argument
  const pause = (ms) => {
    return new Promise(resolve => {
      // Resolving the Promise after the given time
      setTimeout(resolve, ms);
    });
  }
        

Now we will make our window.onload function async to use await.


   window.onload = async () => {
    • • •
  }
        

Now call the pause function inside the loop to get a delay. Change the value pased in pause function to change the speed.


   window.onload = async () => {
    • • • 
      elem.textContent += character;
      await pause(100);
    • • •
  }
        

Congratulations you have made it.

Final full code :-


 // Taking milli seconds as argument
  const pause = (ms) => {
    return new Promise(resolve => {
     // Resolving the Promise after the given time
     setTimeout(resolve, ms);
    });
  }
        
  window.onload = async () => {
    const elem = document.querySelector("#box");
    const str = "Hello everyone I want this text to be typed out =)";
    for (let i = 0; i < str.length; i++){
      let character = str.charAt(i);
      elem.textContent += character;
      await pause(100);
    }
  }
        

Thanks for visiting =)

Hope you learnt something new....