Search

Wednesday, 12 March 2014

Awesome Text Flip Effect using jQuery

This idea popped up in my brains, when I saw a digital ad board in Deccan side chowk in Pune. The ad displayed on it was sporting some cool text, which would animatedly flip its each character to a new character, forming a new cool text.

So that thing in my mind, I have tried to imitate  that in some sense on my client's homepage. But little bit differently.
Check out this fiddle to see it live.
It is amazingly easy using jQuery. Simply styled wiith CSS.

How to do a text flip?

Create a <p> element inside a <div> with following code.

    <div class="textflip">
        <p></p>
    </div>


In .textflip we have a paragraph element, where we are going to append a line or a string which will be flipped. The following script is self explanatory, which gets single character out of a string, and replaces with a single character of another string.

     /************************************
   Create two strings manually, with same lenghts.
   *************************************/
   var str = "0110 1101 1111 0100111";
   var str2 ="Live life king size...";


    /***********************************************
       Loop through each character. 

       Append that character as a <span> to
       <p> in our '.textflip' which is a container.
    ************************************************/ 

    for(var i=0; i<str.length; i++)
    {
      $('.textflip p').append('<span>'+str[i]+'</span>');
     }
      
     
    var halt = 75; // Animation speed
    var j=0;

   
    //Count the number of spans i.e chars in string
    var count = $('.textflip p').children('span').length;

    anim(); // Call animation function


    /************************************
     Animation function
    *************************************/  

    function anim()
    {      
       var n=j;
       $('.textflip p > span').eq(n).animate({
            opacity:0 //By putting opacity zero, vanish the character.
        },halt,function(){
            //This is what to do when character is vanished
            //Bring in the char from second string, display it by opacity:1
            $('.textflip p > span').eq(n).text(str2[n]).css('opacity',1);
                     if(j<=str.length)
                     {
                         anim(); //Animate jth char until j is not an end char.
                                  
                      }
                                   
              });
                                   
               j++;  //next character please!


       }// end of anim() 



Here, anim() is a recursive function which will run unless all characters are not flipped (replaced, actually).

Drawback here is, string length is known. What to do if length is variable? Will you help me to frame the logic for 'dynamic text flip'?

Also Read