Awesome typing effect overlay on images (CSS+JS)
Tags: webdev, css, javascript, beginners
Published: 2020-08-20 12:05:57

<!-- A hero image is a large image that is prominently placed on a web page. It is used to immediately attract a visitor’s attention. A hero image can be used in a portfolio website and today I am going to show you how to add text on top of the image and animate it so that it attracts even more attention. -->

This is a tutorial on how to create a typing effect overlay on images. It was done with pure CSS and JS without any additional libraries. The result is this:

{% codepen https://codepen.io/charalambosioannou/pen/LYNYrVm %}

Here the typing effect was added on a hero image. A hero image is a large image that is prominently placed on a web page (Source: [wikipedia](https://en.wikipedia.org/wiki/Hero_image)). It is used to immediately attract a visitor’s attention. 

# Sections:

1. [Step 1 - Finding the image](#step-1-finding-the-image)
2. [Step 2 - Beautify it using CSS](#step-2-beautify-it-using-css)
3. [Step 3 - Creating the typing effect using JS](#step-3-creating-the-typing-effect-using-js)
    1. [Explanation of JS code](#explanation-of-js-code) 
4. [Full code (codepen)](#full-code)




## Step 1 - Finding the image
 * To start with, we first find a hero image that best suits our needs. My go to website for getting free stock images is https://www.pexels.com/. Once you have found your image, create a new HTML file and add the following script inside the body tag. Replace the hero_image.jpg with the path and name of your own image.

```
<div class="container">
        <img src="hero_image.jpg" alt="Hero Image">
        <div class='console-container'>
            <span id='text'></span>
            <div class='console-underscore' id='cursor'>|</div>
        </div>
    </div>
```
Now your page should look like this:

<img src="https://dev-to-uploads.s3.amazonaws.com/i/t98ymsyu7unqml55qe4a.PNG" width="450">


## Step 2 - Beautify it using CSS

 * Now we will add some CSS to make our image look like a hero image and attract more attention. Add the following code in your CSS file or in a style tab inside the HTML.

```
        @import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@700&display=swap');

        .console-container {
            font-family: 'Open Sans', sans-serif;
            font-size: 4vw;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }

        .console-underscore {
            display: inline-block;
            position: relative;
            color: white;
        }

        .container {
            position: relative;
            text-align: center;
        }
		img {
			width:100%;
		}
``` 

Now your page should look like this:

<img src="https://dev-to-uploads.s3.amazonaws.com/i/tyob92drz9ey0t38cttc.PNG" width="450">


> <i> Don't mind the vertical bar. We will animate it and use it as a cursor in the next step </i>


## Step 3 - Creating the typing effect using JS

* The final step is to add the text we want to animate and actually animate it using JavaScript. To do that add the following block of code which is a function we can call: 

> <b> Important:</b> Place this script <i><u>below</u></i> the div tags which contain the image. Otherwise the typing effect will not work.

```
function typing_effect(words, colors) {

      var cursor = document.getElementById('cursor'); //cursor
      var text = document.getElementById('text') //text

      var blink = true;
      var wait = false;
      var letters_count = 1;
      var temp = 1;

      text.style.color = colors[0]
      window.setInterval(function () { //wait between words when it starts writting
        if (letters_count === 0 && wait === false) {
          wait = true;

          text.innerHTML = '' // leave a blank
          window.setTimeout(function () {
            var usedColor = colors.splice(0, 1)[0] //remove first element and get it as str
            colors.push(usedColor);
            var usedWord = words.splice(0, 1)[0]
            words.push(usedWord);
            temp = 1;
            text.style.color = colors[0]
            letters_count += temp;
            wait = false;
          }, 1000)
        } else if (letters_count === words[0].length + 1 && wait === false) {
          wait = true;
          window.setTimeout(function () { //wait a bit until words finished and start deleting
            temp = -1;
            letters_count += temp;
            wait = false;
          }, 1000)
        } else if (wait === false) { //write words                    
          text.innerHTML = words[0].substr(0, letters_count)
          letters_count += temp;
        }
      }, 120)
      window.setInterval(function () {
        if (blink) {
          cursor.style.opacity = "0";
          blink = false;
        } else {
          cursor.style.opacity = "1";
          blink = true;
        }
      }, 400)
    }
```

* The call to the function is: `typing_effect(words , colors)`. These parameters are lists. The first parameter is a list of strings containing all the phrases that will be displayed. The second parameter is a list of strings containing the colors that each phrase will have. <u> <b><i> Note: </i></b> The two lists don't have to have the same length.</u> The call in my example is:


```
typing_effect(['Hello World', 'My name is Harry', 'I am a programmer', 'This is a JS+CSS example'],
            ['#FFFFFF', 'orange', 'blue', 'yellow']);
```
### Explanation of JS code

If you want to skip the explanation of the code just click [here](#full-code) to go to the next section.

#### Parameters
The code is a single function that takes 2 input parameters. They have been explained in the previous section. 
> The call to the function is: `typing_effect(words , colors)`. These parameters are lists. The first parameter is a list of strings containing all the phrases that will be displayed. The second parameter is a list of strings containing the colors that each phrase will have. <u> <b><i> Note: </i></b> The two lists don't have to have the same length.</u>



#### Variables

`var cursor= document.getElementById('cursor');` - gets the cursor
`var text= document.getElementById('text');` - gets the area which we will add the text
`var blink= true;` - flag that shows/hides cursor 
`var wait= false;`- flag that waits between phrases
`var letters_count= 1;` - int which counts the letters
`var temp= 1;` - int used to increment/decrement `letters_count` 

#### Function

The function consists of 2 `setTimeout` and 2 `setInterval` functions. The first `setInterval` is used to type the phrases, delete them and then type the next one. 
This block of code waits between phrases before starting to type the next phrase.
```
  if (letters_count === 0 && wait === false) {
          wait = true;

          text.innerHTML = '' // leave a blank
          window.setTimeout(function () {
            var usedColor = colors.splice(0, 1)[0] 
            colors.push(usedColor);
            var usedWord = words.splice(0, 1)[0]
            words.push(usedWord);
            temp = 1;
            text.style.color = colors[0]
            letters_count += temp;
            wait = false;
          }, 1000)
}
```

This block of code waits 1 second after the phrase is typed and starts deleting it.
```
 else if (letters_count === words[0].length + 1 && wait === false) {
          wait = true;
          window.setTimeout(function () {
            temp = -1;
            letters_count += temp;
            wait = false;
          }, 1000)
        }
```

This block of code simply types the words 
```
else if (wait === false) {                    
          text.innerHTML = words[0].substr(0, letters_count)
          letters_count += temp;
        }
```

Lastly this block of code makes the cursor blink to simulate the cursor when typing. 

```
window.setInterval(function () {
        if (blink) {
          cursor.style.opacity = "0";
          blink = false;
        } else {
          cursor.style.opacity = "1";
          blink = true;
        }
      }, 400)
```
## Full Code


* The full code in codepen is here:


{% codepen https://codepen.io/charalambosioannou/pen/LYNYrVm %}

THAT’S IT!!!
I hope you find this easy and useful.

Hope you enjoyed it 😄.

Happy Exploring!!