Click here to Skip to main content
Click here to Skip to main content
Go to top

jQuery Typewriter Effect on HTML Text

, 26 Aug 2014
Rate this:
Please Sign up or sign in to vote.
jQuery Typewriter effect on HTML text

Introduction

Sometimes, we see cool effects on text like someone is typing the text using a typewriter. In this example, I am going to show how to do this in HTML using jQuery.

Background

A typewriter effect on text can be done by printing a string, character by character with key stroke audio. Suppose we have a string 'Hello World'. We need to print the 'Hello World' character by character and play an audio everytime while printing a character. And this printing and audio playing process should be done after a defined time interval so that it looks like someone is typing this in realtime.

Using the Code

Here, I'm going to explain the code but I want to let you know that we will not hardcode it for a specific string. Rather than that, we will write a function so that we can apply the effect on multiple texts at a time.

    function typeWriter(l,s,a,i){
        var track = "";
        var len = s.length;
        var n = 0;
        var aud = new Audio(a);
        $(l).text("");
        var si = setInterval(function(){
        if(!aud.paused){    
            aud.pause();
            aud.currentTime = 0;
        }
        var res = track + s.charAt(n);
        $(l).text(res);
        if(s.charAt(n)!==" "){    
            aud.play();
        }
        track = res;
        if(n===len-1){
            clearInterval(si);
        }
        n = n + 1;
    },i);
}

This is our main function for typewriter effect. In this typeWriter function, we are accepting 4 parameters. The first parameter l is the location of the text. By location, I meant the tag name or id name or the class name of HTML tag(s) where we want to show our text(s). The second parameter s is the string/text which we want to put in the location. The third parameter a is the source URL of the audio that will be played while the characters will be printing (Please check this link audio formats and browser support for HTML5 audio). The last parameter i is the time interval of playing audio and printing characters in milliseconds (1 second = 1000 ms).

Let's understand the contents of the function. First, take an empty string track. Later, we will add the characters of the s string respectively. Then, we take the length of the s string in a variable len. We will use len later to stop the effect. Also, we take a variable n and initialize n with 0. We will use n to access the characters of the string by nth position. Then we create an audio object aud with the audio from the URL a. Now, we clear the localtion l with a empty string in case there is something in the location. Now we create a plain JavaScript setInterval function si with i interval. This si function will run after i time interval. That means what is inside the si function will be executed after every i ms. The first thing we will do is checking if the audio is playing currently. That means if the audio is not paused (aud.paused will work for stopped audio too), we will pause it and set the track time into 00:00:00. This thing will stop the previous iterations audio. Then we will take a variable res and save the value of track and the nth character of the s string. Check that for the very first time, the value of track is empty and the value of n is 0. So var res = track + s.charAt(n); statement will take the 0th character of "Hello World" which is 'H'. Then we will set the res into the l location. Remember that currently value of track is "H". In the next iteration, it will be "He". The next thing we will do is skip audio for the spaces because it does not feel good to hear a sound for seeing nothing. Then, we will update the value of track with the last portion of the string that we have shown so far. Then we have to stop the si function using clearInterval else this thing will go on and on. Here we will use the len to compare that if our n points the last position of the string. And the final thing of the si function is incrementing the n by 1 everytime so that we get the character respectively while we use s.charAt(n) function. Now our typeWriter function is done. Now let's see how to use the function on HTML.

Example on Single Text

<!DOCTYPE html>
<html>
    <body>
        <p id="myText"></p>  <!--Hello World will be shown here -->
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script  src="typewriter.js"></script>
        <script>
                (function (){
                    typeWriter("#myText","Hello World","example.ogg",500);
                }());
        </script>
    </body>
</html>

In this single text example, check that I've included the jQuery and typewriter.js just before the </body> tag. After that, I've written a self-invoked JavaScript function and inside that function, I've called the function called typeWriter(). You don't have to use the self-invoked function if you are using an external JavaScript file. Now check that inside the typeWriter() function, I've passed four parameters like typeWriter("#myText","Hello World","example.ogg",500). The first parameter is the target where you want to show the text. As you want to show the text in the paragraph tag, you have to pass the id name with # sign. As this is based on Jquery, the target is just same as the jQuery selector. In the next example, I am going to show it. The second parameter is the text that you want to animate. The third parameter is the location of the audio. The audio format or location depends on you. The fourth parameter is the time interval of showing the next alphabet of any text and playing sound. It's in milliseconds. As I wanted to set 0.5 seconds in my example, I set it to 500. Okay, let's go check the multiple example.

Example on Single Text

<!DOCTYPE html>
<html>
    <body>
        <p id="myText"></p>  <!--Hello World will be shown here -->
        <p class="myText"></p>  <!--Hello Universe will be shown here -->
        <h5></h5>  <!--Hello Galaxy will be shown here -->
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script  src="typewriter.js"></script>
        <script>
                (function (){
                    typeWriter("#myText","Hello World","example.ogg",500);
                    typeWriter(".myText","Hello Universe","example.ogg",500);
                    typeWriter("h5","Hello Galaxy","example.ogg",500);
                }());
        </script>
    </body>
</html>    

The installation is all the same. It's working for multiple texts. And also check that the id, class and tag name selectors are working.

Summary

  • Include jQuery before the </body> tag.
  • Include the typewriter.js after the jQuery.
  • Use the typeWriter(target,text,audio,timeInterval) under the typewriter.js or in a external js file.
  • Audio location should be in the root folder perspective.
  • timeInterval is in milliseconds. For example, use 1000 for 1 second.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

saadixl
Student
Bangladesh Bangladesh
No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web03 | 2.8.140926.1 | Last Updated 26 Aug 2014
Article Copyright 2014 by saadixl
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid