Creating a Typewriting-effect using Vanilla JavaScript
Published: 2023-05-26 15:59:32

---
title: Creating a Typewriting-effect using Vanilla JavaScript
published: true
date: 2022-05-04 17:24:31 UTC
tags: 
canonical_url: 
---

Have you gone to a website and noticed typewriting on the page without you clicking or touching anything, awesome right? yea.  
In this article, I will show you how you can create that feature using vanilla JavaScript.

## **Prerequisites**

- A basic knowledge of JavaScript.
- A basic knowledge of HTML and CSS.
- A code editor and a browser
- Live Server extension or You can load it manually on your respective browsers.

## **Getting Started** 

Well start by creating our HTML file and CSS file, lets call them `index.html` and `index.css`. we will create an `h1` tag underneath the `h1` tag we also need to create a `span` tag which we will give a class name of `txt-type` like the code below.

```
<h1>
        I am Quincy Oghenetejiri A <span class="txt-type" data-wait="3000s" data-words='["Software Developer", "Front End Developer","Backend Developer","Technical Writer"]'></span>
    </h1>

```

In the `span` tag, we have two attributes `data-wait` and `data-words`. The `data-wait` is the time we set for the typing speed while the `data-words` is where we stored the words which we will be typing out and deleting at intervals.

In our `index.css` file, we will target the class txt-type and give a border-right value to provide that mouse typing effect

```
.txt-type {
    border-right: 0.2rem solid black;

}

```

Note: We need to link our index.css file to our HTML file for it to work.

`<link rel="stylesheet" href="/index.css">`

## **Our Result Layout 👇**

![Typing Result 1.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1651679591637/bE-63Vpmo.png)

## **Creating Our JavaScript File**

After we have sorted the above we will have to create our index.js file. We also need to link this file for it work.

```
<script src="./index.js"></script>
</body>
</html>

```

Inside this file we need to create a class and call it `Typewriter`

```
class Typewriter{

}

```

Inside this class we will create a constructor function, a constructor function is a special function that creates and initializes an object instance of a class. This constructor function will take in three values. It also set default values that will be override in the next function we will be creating inside the class.

```
constructor(txtElement,words,wait=3000){
        this.txtElement= txtElement
        this.words = words
        this.txt = ""
        this.wordIndex = 0
        this.wait = parseInt(wait,10)
        this.type()
        this.isDeleting = false

    }

```

After the creation of the constructor function, we will then create another function inside the class `Typewriter` in this function we create two variables and in the first variable as seen in the code below we used the remainder operator (%) to target the current word length which we will be the typing out and then output it into a second variable to get the current word.

```
type(){
         //current index of word 
    const current = this.wordIndex % this.words.length
  //Get Full text of current word
    const fullTxt = this.words[current]

    }

```

The next step involves creating an if and else statement inside the type function to delete and add text characters. The `this.txt`, which has an initial value of an empty string is now updated.

```
// Check if deleting 
    if(this.isDeleting){
          //Remove char
        this.txt = fullTxt.substring(0,this.txt.length - 1)
        }

    else{
         //Add Char 
         this.txt = fullTxt.substring(0,this.txt.length + 1)   
        }

```

Next we will insert the text into an HTML element and set the type speed we want I will be using 300

```
//Insert txt into element 
        this.txtElement.innerHTML = `<span class="txt">${this.txt}</span>`

        // Initial Type Speed
        let typeSpeed = 300

        if(this.isDeleting){
            typeSpeed /= 2
        }

```

The next step involves creating an if and else if statement to check if a word is complete to start deleting or not complete to continue typing and also we use the setTimeout function available in JavaScript to sets the timer(a countdown set in milliseconds) which take the value of the `typeSpeed` variable.

```
//If word is complete
        if(!this.isDeleting && this.txt === fullTxt){
            //Make Pause at end
            typeSpeed = this.wait
            //set delete to true
            this.isDeleting = true
        }
        else if(this.isDeleting && this.txt === ''){
            this.isDeleting = false
            //move to next word
            this.wordIndex++
            //pause before start typing
            typeSpeed = 500
        }

        setTimeout(()=> this.type(),typeSpeed)

```

The next step involves initializing our class on DOM load. We'll first of all create an init function which handles our selection of our HTML class and also initializing our class.

```
//Init App
function init(){
    const txtElement = document.querySelector(".txt-type")
    const words = JSON.parse(txtElement.getAttribute('data-words'))
    const wait = txtElement.getAttribute('data-wait')
    //Init Typewriter
    new Typewriter(txtElement,words,wait)
}

```

And then we load the function created above in the DOM

`document.addEventListener('DOMContentLoaded',init)`

And yass that is all 😅.   
This is all the JavaScript code we wrote.

```
class Typewriter{
    constructor(txtElement,words,wait=3000){
        this.txtElement= txtElement
        this.words = words
        this.txt = ""
        this.wordIndex = 0
        this.wait = parseInt(wait,10)
        this.type()
        this.isDeleting = false
    }

    type(){
         //current index of word 
        const current = this.wordIndex % this.words.length
        //Get Full text of current word
        const fullTxt = this.words[current]

            // Check if deleting 
        if(this.isDeleting){
            //Remove char
            this.txt = fullTxt.substring(0,this.txt.length - 1)
        }

        else{
            //Add Char 
            this.txt = fullTxt.substring(0,this.txt.length + 1)   
        }

        //Insert txt into element 
        this.txtElement.innerHTML = `<span class="txt">${this.txt}</span>`

        // Initial Type Speed
        let typeSpeed = 300

        if(this.isDeleting){
            typeSpeed /= 2
        }

        //If word is complete
        if(!this.isDeleting && this.txt === fullTxt){
            //Make Pause at end
            typeSpeed = this.wait
            //set delete to true
            this.isDeleting = true
        }
        else if(this.isDeleting && this.txt === ''){
            this.isDeleting = false
            //move to next word
            this.wordIndex++
            //pause before start typing
            typeSpeed = 500
        }

        setTimeout(()=> this.type(),typeSpeed)

    }

}

//Init on DOM Load
document.addEventListener('DOMContentLoaded',init)

//Init App
function init(){
    const txtElement = document.querySelector(".txt-type")
    const words = JSON.parse(txtElement.getAttribute('data-words'))
    const wait = txtElement.getAttribute('data-wait')
    //Init Typewriter
    new Typewriter(txtElement,words,wait)
}

```

- [demo link](https://typewriterdemo12.netlify.app/)
- [source code](https://github.com/Te-Stack/Typing-Article-Tutorial-Demo).

## **Conclusion**

Congratulations! You have successfully implemented a typewriter using Vanilla JavaScript. In my next article, I will show you guys how to do this with react using a package called a `typewriter-effect`. Stay tuned and watch this space .