New Aug 8, 2024

How to create an auto “text typing effect” with vanilla JavaScript

The Giants All from Envato Tuts+ Code View How to create an auto “text typing effect” with vanilla JavaScript on code.tutsplus.com

An auto text typing effect is one way to grab a user’s attention. It can give users cues when using an application, and it’s also a way to convey an important message. Let’s make one!

What We’re Going to Create

Let’s have a look at the demo we’re building, just to get ourselves really motivated!

As you’re building this effect, you’ll be able to change the array of words being typed, the speed of the effect, and more!

1. HTML Structure

As so often in this type of tutorial, we’ll create our interface using Bootstrap components. The HTML Structure will contain a  search bar centered at the center of the page, and it will look like this:

1
<div
2
  class="container d-flex justify-content-center align-items-center height"
3
>
4
  <div class="row justify-content-md-center">
5
    <div class="input-group">
6
      <div class="input-group-prepend">
7
        <span class="input-group-text primary" id="search-icon">
8
          <i class="fa fa-search" aria-hidden="true"></i>
9
        </span>
10
      </div>
11
      <input id="text" type="text" class="form-control form-rounded " />
12
    </div>
13
  </div>
14
</div>

To summarise: in our HTML, we have the container element that uses Flexbox to center the content horizontally and vertically.

In the container element, we have a row container that houses the InputGroup.

The InputGroup contains an input text with a search icon prepended to it.

2. Custom CSS 

Let’s tweak things by adding some custom styles. First import a custom Google font and set the height of the body and html to 100% to ensure full viewport height. Ensure the container takes 100% of the body.

1
@import url("https://fonts.googleapis.com/css2?family=DM+Mono:ital,wght@0,300;0,400;0,500;1,300;1,400;1,500&display=swap");
2
3
  body,
4
  html {
5
    height: 100%;
6
    font-family: "DM Mono", monospace;
7
    background-color: aliceblue;
8
  }
9
 .height {
10
  height: 100%;
11
}

Apply the following styles to the text input and the input group:

1
#text {
2
  font-size: 1.52rem;
3
  border-left: none;
4
  border-radius: 0 30px 30px 0;
5
}
6
.input-group-text {
7
  background-color: #fff;
8
  border-radius: 30px 0 0 30px;
9
}

Lastly add the following styles to the icon.

1
i {
2
  font-size: 1.3rem;
3
  margin-left: 1rem;
4
}

3. JavaScript Functionality

With our structure and styling taken care of, let’s move onto the behaviour. Start by getting the text input element.

1
const textElement = document.getElementById("text");

Next, create an array of the words to be typed.

1
const textArray = [
2
    "Software Engineer",
3
    "Data Scientist",
4
    "UX Designer",
5
    "Product Manager",
6
    "Project Manager",
7
    "DevOps Engineer",
8
    "Data Engineer",
9
    "Business Analyst",
10
    "Systems Analyst",
11
    "Web Developer",
12
    "App Developer",
13
    "Network Engineer",
14
    "Frontend Developer",
15
    "Backend Developer",
16
    "Full Stack",
17
    "Scrum Master",
18
    "Technical Support",
19
    "Database Admin",
20
  ];

Define the following variables:

1
let pipe = true;
2
let index = 0;
3
let speed = 200;
4
let isTyping = true;
5
let textIndex = 0;
  • pipe : this variable will  control the visibility of the pipe symbol ( | ) to  represent a blinking cursor
  • index =0 : will be used to track the current position of the character being typed. 
  • speed =200 :represents the typing speed in milliseconds
  • isTyping = true;  : used to determine whether the text is being typed or deleted
  • textIndex : indicates the item from the textArray being typed.

Next create a function called typeText().

1
function typeText() {
2
    
3
}

Inside the function, we’ll start by getting the first item from the textArray and adding the pipe (|) character at the end of the text.

1
function typeText() {
2
  let text = textArray[textIndex];
3
  if (pipe) {
4
    text += "|";
5
  }
6
}

To simulate the typing effect, we’ll create a typing block that checks if isTyping is set to true.

1
function typeText() {
2
  let text = textArray[textIndex];
3
  if (pipe) {
4
    text += "|";
5
  }
6
7
  if (isTyping) {
8
    if (index < text.length) {
9
      textElement.value += text[index];
10
      index++;
11
    } else {
12
      isTyping = false;
13
    }
14
  }
15
}

Inside this block, let’s create an inner if statement to check if index is less than the length of the text. If this condition is true, it means there are still characters in the text string which haven’t been typed.

If there are still characters in the text string, we will append the character at the current index to the value of the text element. After adding the character, we will increment the index using index++ to ensure that the next character in the string is also appended to the value of the text element.

In the else statement of the inner loop, we will set isTyping to false to stop the typing.

After the loop, we’ll set up a setTimeout function to recursively run the typeText() function, which will continuously add characters to the text element’s value every 200 milliseconds until all characters from the text string have been appended.

The typeText() function now looks like this:

1
function typeText() {
2
  let text = textArray[textIndex];
3
  
4
5
  if (pipe) {
6
    text += "|";
7
  }
8
  if (isTyping) {
9
    if (index < text.length) {
10
      textElement.value += text[index];
11
      index++;
12
    } else {
13
      isTyping = false;
14
    }
15
  }
16
  setTimeout(typeText, 100);
17
}
18
19
typeText();

In deleting mode, when isTyping is now set to false, we will create an inner if statement that checks to ensure that index is greater than 0. This ensures that the deleting happens as long as there are characters to be deleted.

If the condition is true, we will decrement the index and use the slice() method to remove the last character of the string. 

In the inner else statement, i.e., if index < 0, it means all the characters of the string have been deleted; we will set isTyping to true and assign textIndex to the next item in the textArray.

Update the function as follows:

1
function typeText() {
2
    let text = textArray[textIndex];
3
    if (pipe) {
4
      text += "|";
5
    }
6
   
7
    if (isTyping) {
8
    if (index < text.length) {
9
        textElement.value += text[index];
10
        index++;
11
    } else {
12
        isTyping = false;
13
    }
14
}
15
16
17
setTimeout(typeText, speed);
18
}

The deleting functionality will repeatedly run after every 200 seconds, as defined by the speed variable.

And here is a reminder of the demo!

Conclusion

In this tutorial, we learned how to use Vanilla JavaScript to build an auto text typing effect which rotates through an array of words. Hopefully this tutorial will serve as a foundation for building more advanced projects!

Scroll to top