I started writing some JS code to cause a variables value to increase over time, up to a target value, with some form of \'ease-in\'.
I realised that jquery already
Yes, you can animate variables. Demo here
$({ n: 0 }).animate({ n: 10}, {
duration: 1000,
step: function(now, fx) {
$("div").append(now + "<br />");
}
});
In this example, I am animating n from 0 to 10 in 1 second. The step
function is called during animation and from there you can retrieve the current value in now
.
Personally, I used this technique to animate several css properties simultaneously in a non linear fashion.
Animate runs by modifying the value of properties declared in JS objects. Although animate
is designed to change CSS scalar values, it can also safely be used for any generic property, as long value
is a scalar one.
In fact, you can think of CSS as a set of JS objects, where properties are for example, top
, margin
etc.
Note that the following scripts do the same. They change CSS left
from 0 to 10
$("#test").css('left', 0).animate({ left: 10 }, 1000);
is the same as
$({ left: 0 }).animate({ left: 10 }, {duration: 1000, step: function(now, fx) {
$("#test").css('left', now);
}});
or, without using the now
parameter
var obj = { left: 0 };
$(obj).animate({ left: 10 }, {duration: 1000, step: function() {
$("#test").css('left', obj.left);
}});
To see them in action click here