Saturday, February 19, 2011

CoolJS : Simple JavaScript Text Animation

Usually I spend my weekends doing some kind of coding or the other. My personal favourite is JavaScript. I love the simplicity and power that JavaScript has as a programming language.Add to this a couple of nice JS Libraries, and the effort becomes worth sharing !

I have used mootools to create a script where a simple piece of text like this can be changed into an impressive animation.

Without wasting anymore time, I would like to dwell into the code right away … !!!

First I would like to show the HTML setup required :

 

   1:  <html><head>


   2:  <script type="text/javascript" 


   3:  src="https://ajax.googleapis.com/ajax/libs/mootools/1.3.0/mootools-yui-compressed.js" >


   4:  </script>


   5:  <script type="text/javascript" src="cooljs-1.0.js" >


   6:  </script>


   7:   


   8:  </head>


   9:      <body onload=loadCoolJS() >


  10:      <p>&nbsp;</p>


  11:   


  12:      <p>Text below is animated. Hover mouse to see it in action</p>    


  13:          


  14:      <p>&nbsp;</p>


  15:          


  16:      <div class="cooljs" style="font-size:22px;">


  17:      This is some sample text which i intend to animate.


  18:              


  19:      </div>


  20:          <p>&nbsp;</p>


  21:          <div>


  22:          Here is some normal text.


  23:          </div>


  24:      </body>


  25:   


  26:  </html>




 



The code need not be explained,  but just for the heck of it, I am including 2 javascipt files, first one is the mootools JS library hosted at Google, and the second one is the JS code that I wrote.



I call the function loadCoolJS()when the document loads, whose functionality I would describe later. The JS code automatically picks the element which have the CSS class named “cooljs”,and animates the inner text.



Note: Make sure there is no HTML inside the element which you are declaring as cooljs. That’s all at the HTML end.



Moving to the javascript setup, which surely needs some explaining, here we go :




   1:  var bg = document.bgColor; //background color


   2:  var fg = 'black';   //foreground color


   3:  var ig = 'red'        //initial color


   4:  if(bg=='')


   5:      bg='white';


   6:   


   7:   


   8:  function  loadCoolJS(){


   9:   


  10:  $$('div.cooljs').each(function(item,index){


  11:   


  12:  var s = item.innerHTML.trim();


  13:  item.innerHTML='';


  14:   


  15:  for(i=0;i<s.length;i++){


  16:   


  17:  var sp = new Element("span",{


  18:              styles:{


  19:              opacity:0.01,


  20:              cursor:'pointer'


  21:              },


  22:              events:{                


  23:              mouseover:function(){eMouseOver(this);},


  24:              mouseout:function(){eMouseOut(this);}            


  25:              }


  26:              


  27:              });


  28:   


  29:  sp.set('html',s.charAt(i));


  30:  sp.mouseOverFx = new Fx.Tween(sp);


  31:  //console.log(sp);


  32:  item.grab(sp);


  33:  }


  34:   


  35:  });


  36:  }


  37:   


  38:  function eMouseOver(e){


  39:  e.mouseOverFx.cancel();


  40:   e.mouseOverFx.start('opacity',0.01,1);


  41:  }


  42:   


  43:  function eMouseOut(e){


  44:  e.mouseOverFx.cancel();


  45:  e.mouseOverFx.start('opacity',1,0.01);


  46:  }





Mere 46 lines of code! That’s the beauty of JS. Anyways moving forward line# 1-5 do nothing but setup the color, which as a matter of fact I am not using at the moment. I keep the text style intact as it was in the cooljs element.





In line# 10 I iterate through all DIV elements of class type cooljs and for each element do the following



First I extract the text contained in the DIV tag in line#12. Then, I remove whatever text the tag has in line# 13, to be replaced by HTML code generated by me via code.



Then I iterate over each character in the extracted text, creating a SPAN tag out of each,setting 2 CSS properties: opacity(0.01) and cursor,and adding 2 event handlers mouseover and mouseout.. The opacity has been set to nearly invisible so the the text is hidden initially.



At line# 29 I set the text inside the span. ( 1 character for each span).



At line #30 I create an Object of Fx.Tween over the created span, and add it to the SPAN DOM object. Fx.Tween is provided by the mootools JS library. This performs the actual animation over an element, tweening the specified CSS property from x to y over a specified time interval.



At line# 32, I insert the created SPAN into the DIV from where I took the text. This process happens for each character inside the DIV tag.



Then comes the event handler functions, at line#38 I have the mouseover event handler. The function gets the SPAN item itself as the parameter, since at line#23 and 24, “this” is passed to the event handler code, which means the current object in scope i.e. sp in this case.



At line# 39 any currently running animations are cancelled, and at line# 40 a tween starts, for the CSS property opacity, changing it from 0.01 to 1, which means from nearly invisible to perfectly visible.



A similar code exists for mouseout event handler, the only difference being that this time the opacity changes from 1 back to 0.01.



The logic is simple, the code is small, and the demo can be found at http://bpnarain.com/cooljs/ .



I would love to get some feedback over this. If you are interested in using this code somewhere else, you are free to do so, and you are free to ask for my help if you are incapable of it.