Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Perform Different Text Animations With jQuery

TwitterFacebookRedditLinkedInHacker News

When it comes to my name, there is often a lot of confusion. On social media sites such as Twitter, GitHub, and similar, I often go by nraboy which is the first character of my first name (Nic) followed by my last name (Raboy). When people see that, they often think of The National Rifle Association (NRA), which is obviously unrelated to what I’m trying to present myself as. However, due to the NRA acronym being similar to my online handles, I get included on a lot of crazy conversations that I really don’t want to be a part of. In fact, it is one of the main reasons why the blog was rebranded from blog.nraboy.com to thepolyglotdeveloper.com.

Out of this I decided to create an animation showing the obvious. Rather than putting my video editing skills to the test, I decided to create an animation using jQuery and simple JavaScript. In this tutorial we’re going to play around with some text animations using jQuery.

To get an idea of the animation that I had created, take a look at the following animated image:

Animate Text with jQuery

As you can see, there are three different effects going on. The first animation is the fade in of each character followed by an animated margin being added between the two words. Finally a block of words fades in. To create these effects we have to take into consideration delays as well as the animation effect themselves.

We’re going to start by reproducing what I’ve done, and then add some other features to the animation as well. On your computer, create an index.html file with the following boilerplate code:

<!DOCTYPE html>
<html>
    <head></head>
    <body>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script>
            $(document).ready(() => {
                // Animation logic here...
            });
        </script>
    </body>
</html>

In the above code we’ve just included the jQuery library and prepared our script when the document becomes ready. The next step is to define the DOM components that we wish to animate:

<!DOCTYPE html>
<html>
    <head></head>
    <body>
        <div class="centered">
            <span class="firstname">n</span>
            <span class="firstname">i</span>
            <span class="firstname">c</span>
            <span class="lastname">r</span>
            <span class="lastname">a</span>
            <span class="lastname">b</span>
            <span class="lastname">o</span>
            <span class="lastname">y</span>
            <div class="info">It's my name, not the NRA</div>
        </div>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script>
            $(document).ready(() => {
                // Animation logic here...
            });
        </script>
    </body>
</html>

In the above code you’ll notice that we have each character as a separate <span> tag. This will allow us to give a different effect to each character, something that can’t easily be done if we use a single string. The string that we do have works because we plan to animate the entire string at once, not character by character.

If we wanted to get a little fancy, we can define our styles for each element like the following:

<style>
    body {
        background-color: silver;
    }
    .centered {
        background-color: #555555;
        border: 1px solid #000000;
        color: #FFFFFF;
        width: 550px;
        padding: 15px;
        height: 150px;
        position: fixed;
        top: 50%;
        left: 50%;
        margin-top: -50px;
        margin-left: -200px;
    }
    .info {
        font-size: 30px;
        display: none;
    }
    span {
        font-size: 100px;
        font-weight: bold;
    }
    .firstname:not(:first-of-type) {
        display: none;
    }
</style>

However, it isn’t absolutely necessary because the id and class attributes are more for jQuery than our style information. Now we can focus on the actual jQuery logic which will perform the animations. Within the <script> tag of our index.html file, include the following:

<script>
    $(document).ready(() => {
        setTimeout(() => {
            var firstnameLength = $(".firstname").length;
            $($(".firstname").get()).each((i, e) => {
                $(e).delay(500 * (i - 1)).fadeIn(500);
                if(i >= firstnameLength - 1) {
                    $(e).animate({
                        "margin-right": "25px"
                    }, 500);
                    $(".info").delay(700 * i).fadeIn(1500);
                }
            });
        }, 1000);
    });
</script>

So what is happening in the above code?

First we are setting a timeout because we don’t want the animation to immediately happen. We want to wait a moment and then perform the animation. When we start the animations, we first determine how many <span> elements have the firstname class name. This is important because we need to know when to queue the next part of the animation.

Using jQuery, we can loop through each of the <span> elements, add a delay time, and add a fade time. The goal is to increase the delay between each of the elements by 500ms. This means the first character will not delay, the second character will delay 500ms, the third 1000s, and so on and so forth. The actual animation will occur over the span of 500ms for each element.

After all of the <span> elements have their delays and animations defined, we can add an animation to the final element which adds a margin. We can also define an animation for the string. The delay is a little longer on the string because we want to make sure everything has finished first. We can’t just animate because the loop will finish a lot quicker than the animations. The loop doesn’t go at the same speed as the animations.

Now let’s change it up a bit. What if we wanted to do that typing text effect in reverse? We might try the following:

<script>
    $(document).ready(() => {
        $(".lastname").first().css("margin-left", "25px");
        setTimeout(() => {
            var firstnameLength = $(".firstname").length;
            $($(".firstname").get().reverse()).each((i, e) => {
                if(i < firstnameLength - 1) {
                    $(e).delay(500 * i).fadeOut(300);
                } else {
                    setTimeout(() => {
                        $(".lastname").first().animate({
                            "margin-left": "0px"
                        }, 500, () => {
                            $(".info").fadeIn(1500);
                        });
                    }, (500 * i));
                }
            });
        }, 1000);
    });
</script>

In the above example, we are first setting the margin on the last name because the first name will be animating in reverse. When coming up with our loop, we are first reversing the <span> elements so that we can animate in the reverse order. We don’t want to animate the first character which is the last in the loop. Instead, we want to create another timeout, animate the margin on the last name, and then fade in with our string. This time around, instead of working with a bunch of delays, we are animating the string via the completion callback of the animate function. Different ways are available to solve a problem.

Conclusion

You just saw how to animate text on a web page using jQuery and simple JavaScript. I gave an outrageous example regarding the misinterpretations of my name, but I’m sure you can probably come up with a more realistic example on when to use such animations.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in C#, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Unity. Nic writes about his development experiences related to making web and mobile development easier to understand.