This is a function I wrote for my new website I'm working on. Unlike the Mootools and jQuery animation functions, this allows you to animate anything with a numeric value. Usage is as follows:
[syntax]aniAttr(assign value to object function, start value, end value, duration[, done function[, frames]]);[/syntax]
1. As the animation progresses, the first argument (a function) is provided with the current position. That makes this function very versatile. This trait is necessary because passing by reference is impossible in Javascript.
2. Since the object being changed is never passed to the function, a start value must be provided.
3. The terminal state of the animation
4. The duration argument is the time the animation will last in milliseconds.
5. The done function (optional) is called when the animation is finished.
6. Frames (optional) gives you the option of specifing the total number of frames. It has three options: A) left undefined it will give you a fixed 60fps, B) a positive integer, or C) zero or any negative number will give you a frame count equal to the absolute difference between the start value and the end value. If you want to specify the number of frames, but not the done function, pass null as the done function.
Here is the code.
Code: Select all
function aniAttr(func, ovalue, dvalue, dur, done, frames) {
if (done == undefined || done == null) var done = function () {};
if (frames == undefined || frames == null) var frames = (dur/1000) * 60;
if (frames < 1) frames = Math.abs(Math.round(dvalue) - Math.round(ovalue))
var fps = frames / (dur / 1000);
var step = (dvalue - ovalue) / frames;
var i = 0;
var t = setInterval(function () {
if (i < frames) {
if (i == frames-1) {
ovalue = dvalue;
} else {
ovalue += (dvalue - ovalue) / (frames - i);
}
func(ovalue);
i++;
} else {
clearInterval(t);
done();
}
}, 1000/fps);
}Code: Select all
aniAttr( function (x){
document.getElementById('box').style.top = x+'px';
}, 0, 30, 600, function (){
alert('box moved!');
});Code: Select all
aniAttr( function (x){
document.getElementId('box').innerHTML = 'Only ' + x + ' seconds left!';
}, 10, 0, 10000, function () {
alert('time is up!');
}, 0);Edit: updated