Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it okay to use .animate with 0 duration all the time? Is there a better alternative?

I've grown used to code my jquery animation by doing the following.

  1. Set the initial state of the element (things like width, height, top, left, opacity, etc...) using either css or javascript. This initial state is the state at the end of the animation.

  2. Use .animate with 0 duration to move the element to the state in which elements are at the beginning of the animation.

  3. Use a regular .animate with the appropriate duration to do the animation in which at the end, the elements are back to state in step 1.

Here is an example.

/* css file */
.animatedObject
{
    width:60%;
}

// javascript file
$('.animatedObject')
    .animate({width: '-=20%'}, 0)
    .animate({width: '+=20%'}, 1000);

There are several advantage using this code at least for me. First, it looks clear to me what I'm trying to animate. Second, if javascript is disabled, the object would be at the end state of the animation which is often where I want it to be for graceful degradation. Third, objects can change position slightly for adjustments using css and the animation would still look largely the same.

The reason I'm not using the .css is that it if I try to replace the animate with 0 duration with the .css method, I would get differing animation starting point. I don't think it support += or -=, or if it does, it behaves differently.

So, is this a good way to do this? What is the industry standard way?

like image 730
BringMeAnother Avatar asked Jul 16 '13 21:07

BringMeAnother


1 Answers

Well you could still use .css():

var anObj = $('.animatedObject');
anObj.css("width", anObj.css("width") - (20 / anObj.css("width"))).animate({
    width: '+=20%'
}, 1000);

I believe this would work faster.

Edit:

I did a little benchmark for you, using jsperf.com. Here are my results (using Google Chrome):

.animate({}, 0)

Code:

$('.animatedObject')
    .animate({width: '-=20%'}, 0)
    .animate({width: '+=20%'}, 1000);

End Results:

10,013 operations per second
±7.48%
fastest

.css();

Code:

var anObj = $('.animatedObject');
anObj.css("width", anObj.css("width") - (20 / anObj.css("width"))).animate({
    width: '+=20%'
}, 1000);

End Results:

2,477 operations per second
±6.39%
75% slower

Conclusion

Keep the animation function. It turns out using .css() is actually slower. I guess it's the fact that you have 2 extra functions. It's not worth it. This was actually a surprise to me as I thought .css() would function faster than it did. Test this yourself in your browser!

like image 145
Shawn31313 Avatar answered Oct 17 '22 03:10

Shawn31313