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

I'm used to coding jquery animations by following these steps.

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

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

  • Use regular .animate with the appropriate duration to make an animation in which at the end the elements return 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 advantages to using this code, at least for me. Firstly, it’s clear to me that I'm trying to revive. Secondly, if javascript is disabled, the object will be in the final state of the animation, where often I want it to be elegant degradation. Thirdly, objects can slightly change the position for settings using css, and the animation will still look basically the same.

The reason I am not using .css is that if I try to replace aimate with a duration of 0 using the .css method, I will get a great starting point for the animation. I don't think it supports + = or - =, or if so, it behaves differently.

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

+7
javascript jquery html
source share
1 answer

Well, you can still use .css() :

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

I believe this will work faster.

Edit:

I made a small guide for you using jsperf.com . Here are my results (using Google Chrome ):

.animate({}, 0)

The code:

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

The final results:

10,013 operations per second
±7.48%
fastest

.css();

The code:

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

The final results:

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

Conclusion

Save the animation function. Turns out using .css() is actually slower. I assume you have 2 extra features. It is not worth it. This was a surprise to me, as I thought .css() would function faster than it was. Check it out yourself in your browser!

+4
source share

All Articles