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 does this in it's .animate() method. Of course, the method is for manipulating CSS properties, not general variables.
My question is, is there anything that can be done to hack it so that the method affects a variable, rather than a CSS property?
The animate() method is typically used to animate numeric CSS properties, for example, width , height , margin , padding , opacity , top , left , etc. but the non-numeric properties such as color or background-color cannot be animated using the basic jQuery functionality. Note: Not all CSS properties are animatable.
The jQuery animate() method is used to create custom animations.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With