DEV Community

Cover image for Awesome typing effect overlay on images (CSS+JS)
Charalambos Ioannou
Charalambos Ioannou

Posted on

Awesome typing effect overlay on images (CSS+JS)

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:

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). It is used to immediately attract a visitor’s attention.

Sections:

  1. Step 1 - Finding the image
  2. Step 2 - Beautify it using CSS
  3. Step 3 - Creating the typing effect using JS
    1. Explanation of JS code
  4. Full code (codepen)

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

Now your page should look like this:

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

Now your page should look like this:

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

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:

Important: Place this script below 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)
    }
Enter fullscreen mode Exit fullscreen mode
  • 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. Note: The two lists don't have to have the same length. 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']);
Enter fullscreen mode Exit fullscreen mode

Explanation of JS code

If you want to skip the explanation of the code just click here 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. Note: The two lists don't have to have the same length.

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

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

This block of code simply types the words

else if (wait === false) {                    
          text.innerHTML = words[0].substr(0, letters_count)
          letters_count += temp;
        }
Enter fullscreen mode Exit fullscreen mode

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

Full Code

  • The full code in codepen is here:

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

Hope you enjoyed it πŸ˜„.

Happy Exploring!!

Top comments (10)

Collapse
 
thomasbnt profile image
Thomas Bnt β˜•

Better than typeitjs. Thanks 🎈

Collapse
 
charalambosioannou profile image
Charalambos Ioannou

Thank you so much. Really appreciate it πŸ™πŸ™

Collapse
 
sabarishcodes profile image
Sabarish Rajamohan

I was actually searching for this effect. Glad I found your post. Thanks, much !!

Collapse
 
charalambosioannou profile image
Charalambos Ioannou

No problem I'm glad I could help πŸ˜€πŸ˜€

Collapse
 
andrewbaisden profile image
Andrew Baisden

Oh wow pretty cool!

Collapse
 
charalambosioannou profile image
Charalambos Ioannou

Thank you very much!! πŸ˜€πŸ˜€

Collapse
 
prafulla-codes profile image
Prafulla Raichurkar

Awesome! 😁

Collapse
 
charalambosioannou profile image
Charalambos Ioannou

Thank you!! πŸ˜€ πŸ˜€

Collapse
 
harshvats2000 profile image
HARSH VATS

Awesome dude.

Collapse
 
charalambosioannou profile image
Charalambos Ioannou

Thanks!! πŸ™‚πŸ™‚