Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can jQuery's .animate() method be made to affect variables, rather than CSS properties?

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?

like image 772
UpTheCreek Avatar asked Feb 17 '12 06:02

UpTheCreek


People also ask

Can the animate () method be used to animate any 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.

Which among the given below methods in jQuery can be used to create custom animations with exclusive control?

The jQuery animate() method is used to create custom animations.


1 Answers

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

like image 103
Jose Rui Santos Avatar answered Oct 06 '22 13:10

Jose Rui Santos