JavaScript
jQuery

Jitter each letter in a text using javascript – Part Two


This is the second part of the Jittery Text tutorial. Here we will see how to shake individual letter of a text using javascript. We will get to see some new functions in javascript like split() and also get to know how to create and push an array. We will also see how to use loops within a loop to get this done.

In the FIRST PART of the tutorial we saw how to make any element on the whole to shake and jitter in its own place. So kindly do visit that tutorial to understand how we create random numbers and execute the plan. That knowledge will act as a base for this tutorial, because we will not be touching the topics already discussed.

How it is done?

Unlike other tutorials where I share the code first and then explain it later, in this tutorial I would like to explain the method and then show you the code. Alternatively you can download the source code from the link above.

First to make each letter inside any text shake we have to separate them. Once each letter is separated we will enclose them inside a span tag. Span tag is an inline element. So even after inserting them they still arrange the text in the same line and will not distort the text. At the same time we get control over individual letter of the text.

To accomplish this we will be using split() function from javascript. W3Schools defines split() function as “The split() method is used to split a string into an array of substrings, and returns the new array. Tip: If an empty string (“”) is used as the separator, the string is split between each character.” The tip actually answers our problem.

So in out case we do with the following code.

var split_element = ".split";
var split_contents = $(split_element).text().split("");

First we fetch the element to be split and store it in split_element variable. Then we get the text of it using jquery’s text() function and then apply the above said split(“”) function to it. This will give us an array variable split_contents.

Wrap it in Span

Now the we have an array of each individual text we can use a for loop to run the array and assign values. Lets take one step at a time here.

for (i in split_contents){ // FOR LOOP TO SPLIT THE TEXT
       
    if((split_contents[i]) == " "){ //CHECK IF THERE IS SPACE
        split_text = split_text + '<span>&nbsp;</span>';
    } else {
        split_text = split_text + '<span>' + split_contents[i] + '</span>';
    };
}; //END FOR LOOP TO SPLIT THE TEXT
$(split_element).html(split_text);

In the ‘for’ loop we assign a variable ‘i’ as the index number of the array object split_contents. This is actually an easy method as it loops till all the index values inside the array are exhausted.

Now inside the for loop we create an if statement to see if any array value stores a space. This is very much possible because any sentence is made of words and space. So when we split them using the javascript function the space in the sentence gets assigned to an array value. So using the if statement we check for any spance and replace it with ‘ ‘. If not space exists we wrap the split_contents with index number inside a span and add it to the split_text variable. In each loop the index number is incremented from 0 and thus we get each value of the array object split_contents. Like this we slowly build up the split_text variable. After the loop is exhausted now the split_text variable will have the entire text element wrapped with span tag. Its time to replace that into our DOM (Document Object Model) and we easily can do it with jquery .html() function.

Create an random number for each span and assign to it.

First we find the length of the split sentence and store in to split_length variable. We do it with the following code.

var split_length = split_contents.length;

Then using a normal for loop we we generate the random number and assign it to the span tag.

var rand_values = []; //CREATE ARRAY
// GENERATE RANDOM NUMBERS
for (n=0; n<split_length; n++){
    var m_rand = Math.random();
   
    //Multipy by the least number to get very jittery. Here its 2
    var rand_num = Math.floor((Math.random()*1.2)+1);
   
    // Decide if the generated number is negative or positive.
    var m_rand = m_rand < 0.5 ? -1*rand_num : rand_num;
   
    //Create the array
    rand_values.push(m_rand);
   
    if (m_rand%2 == 0) {
        //ADD n+1 because loop starts from 0 and there is no slector which is nth-child(0);
        $(".split span:nth-child("+(n+1)+")").css({
            top: rand_values[n]
        });
    } else {
        //ADD n+1 because loop starts from 0 and there is no slector which is nth-child(0);
        $(".split span:nth-child("+(n+1)+")").css({
            left: rand_values[n]
        });
    }
   
} //END FOR LOOP RANDOM NUMBERS

With split_length as the limiter we run the loop starting from n value as 0. So this loop will run for the entire length of the sentence helping us to generate a random number for each span tag and assign to it. The process of creating and assigning a random number are all the same as we discussed in the first part of the tutorial. Because we are totally handling this dynamically here there are two major changes/additions.

First we generate m_rand variable with the random number and using push() function from javascript we create the rand_values array object. Then using the nth-selector from jquery we select the nth span and assign the value to it. And because this happens in a for loop that runs through the entire length we can be sure that a random value is generated for each span.

Let’s pep it up!

Though the above method works it is usually slow and after testing the random values are not so random. This did not give the whole animation the required shake. So I thought of enclosing the whole for loop with another for loop. This way the random numbers generated are more random and the letter shakes and jitters better. Hence the following code.

// LOOP FOR THE STRING LENGTH
for (i in split_contents){
   
    var rand_values = []; //CREATE ARRAY
    // GENERATE RANDOM NUMBERS
    for (n=0; n<split_length; n++){
        var m_rand = Math.random();
       
        //Multipy by the least number to get very jittery. Here its 2
        var rand_num = Math.floor((Math.random()*1.2)+1);
       
        // Decide if the generated number is negative or positive.
        var m_rand = m_rand < 0.5 ? -1*rand_num : rand_num;
       
        //Create the array
        rand_values.push(m_rand);
       
        if (m_rand%2 == 0) {
            //ADD n+1 because loop starts from 0 and there is no slector which is nth-child(0);
            $(".split span:nth-child("+(n+1)+")").css({
                top: rand_values[n]
            });
        } else {
            //ADD n+1 because loop starts from 0 and there is no slector which is nth-child(0);
            $(".split span:nth-child("+(n+1)+")").css({
                left: rand_values[n]
            });
        }
       
    } //END FOR LOOP RANDOM NUMBERS

}; //END FOR LOOP TO SPLIT THE TEXT

setInterval() to the rescue

Finally we need all this to happen repeatedly over a period of time and so comes setInterval() function to the rescue. We enclose all the for loops inside the setInterval() function so that it is repeated over 10 milliseconds. To understand the working of setInterval() please read the first part of the tutorial.

Conclusion

I would suggest using this in any UI Design where you want some jazzy look. For example headers of any section like portfolio or pages. The end is just your creativity. Do let me know where and how you have used this script. It will be really glad if you could share the links where you have used this script. Looking forward to a good discussion.

Thank you for reading.

Latest Comments

Leave a Reply

comment on this article