Monday, April 23, 2012

Generic animation in javascript

The following function uses a method in javascript known as a “closure.” 
http://www.jibbering.com/faq/faq_notes/closures.html

Given a property, a start value, an end value, a step, a delay, and a function to callback when finished.  The function will start the value at the start and change the value in either step size or based on the delay.
 
var register = [];
var count=[];

function Animate (prop, start, end, step, ms, setval, callback){

 if (prop == null || setval == null)
  return;

 var delay=0;
 while (delay < 50){
  delay = Math.abs (ms / ((start - end)/step));
  ((start-end) < 0)?step++:step--;
 }
 ((start-end) < 0)?step--:step++;

 if ((start>end)?(step>0):(step<0)){
  setval(prop, end);
  return;
 }

 var current = start;
 setval(prop, current);

 count++;
 var mycount = count;
 function stepfunc (){
  current += step;
     if ((start>end)?(current>end):(current<end)) {
   setval(prop, current);
         setTimeout(stepfunc, delay);
        } else {
   setval(prop, end);
   //register[mycount]=null;
   if (callback)
    callback(prop, start, end, step, ms, setval, callback);
  }
 }

    setTimeout(stepfunc, delay);
}

A closure is a function inside another function that retains access to the variables in the outer function.   It exists as long as there is a reference to itself and it can retain the reference itself. So it is a way to create a thread of execution in javascript that executes on it’s own.

In the case of the animate function, the stepfunc is the closure in this case.  It calls itself in the callback function.

Now, let’s say that you want to slowly open a box on the screen up.
 
function openbox (){
    box=document.getElementById('Windowtr');  // Get the object.
    Animate(box, 0, 100, 10, 100, nop, openboxrd);
}
function openboxrd(box){
    Animate(box, 0, 50, 1, 500, changewidth, openboxrd2);
}

function openboxrd2(box){
    Animate(box, 0, 50, 1, 500, changeheight, null);
}
function changeheight(obj, value){
    obj.style.height = "" + value + "pt";
}
function changewidth(obj, value){
    obj.style.width = "" + value +"pt";
}

In the html document this java script is included with this line in the head of the html document:

<script id="NAME10001" type="text/javascript" src="demo.js" />
 
The box we are opening is defined in the body with:

<div id="Windowtr" style="z-index: 20000; position: absolute;
 width: 0px; height: 0px; display: visible; left: 100px;
 top: 50px; background: #00FFFF; border: 2px solid Black;
 position: absolute; text-align: right; z-index: 20000;"></div>
 
And you can tie this to a button click on text like this: 
 
<P><A HREF="#" onclick="openbox(); return false;" class='popup'>Open Box</A>.</P>
 
 

No comments:

Post a Comment