23

I'd like to do the strangest thing: make a value change with animate which isn't a css property but just a variable.

I need this because I want to rotated an element when an user clicks on its border. So I need to animate the angle value and then use it in a custom drawing algorithm.

I tried to use css property of an hidden DIV just to store it's angle value and animate it, but it doesn't work properly.

Can anyone helps me with it please?

1
  • According to the JQuery animate doc api.jquery.com/animate: "In addition to style properties, some non-style properties such as scrollTop and scrollLeft, as well as custom properties, can be animated." Commented Oct 16, 2012 at 14:21

3 Answers 3

67

Just stumbled upon this while searching for the same thing and the correct answer appears to be

$({foo:0}).animate({foo:100}, {
    step: function(val) {
        // val takes values from 0 to 100 here
    }
})

Found on http://james.padolsey.com/javascript/fun-with-jquerys-animate/

Sign up to request clarification or add additional context in comments.

5 Comments

This is what I was looking for. I don't want any DOM element's attributes, styles or JavaScript properties changed.
Note that the starting value must be zero. So, it's probably easier to assume an ending value of "1" and do your own progress calculation: val = start_val*(1-val) + end_val*val;
@Ch'marr jQuery seems to support any initial value right now.
Why does the starting value have to be zero? That's ridiculous. Also, restricting the range from zero to one and doing your own easing calculation almost defeats the purpose of using this method in the first place.
where do you set the duration?
2

Annoyingly it's not possible to run the animate function without actually supplying some CSS properties for it to work on (it doesn't give you the values in between).

You don't need to even have the animation working on the actual element (or variable) you want to change so it's possible to hack it to work using the step argument as described by @Andrew like so:

$('<div/>').css({ height: _your_start_value }).animate({
    height: _your_end_value
}, { 
    step: function (currentValue) {
        //do what you need to with the current value..
    }
});

However, this is pretty inefficient as it's changing the (although unattached) element's height CSS property needlessly. It's better to just use a "tweening" library such as Tween JS to do this kind of thing.

Comments

0

If you are looking to "spin" something, you can do that with css and therefore, you can use the jQuery animate function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.