views:

28

answers:

2

jQuery 1.4.2's animate() API spec is

.animate( properties, [ duration ], [ easing ], [ callback ] )

but it seems that we can supply duration, callback, and no easing

.animate({left: '+= 100'}, 600, doThis)

and it will work.

But if we supply easing and callback and no duration

.animate({left: '+=100'}, 'swing', doThis)

then the easing won't be taken into effect. So what exactly is the API supposed to be?

Update: please see my answer below.

+2  A: 

Normally jQuery determines optional parameters by types, e.g. this works:

$('.class').animate({opacity: 'toggle'}, doThis);

But in the case of duration/easing, since they're both strings it can't (and if there's a single string, it assumes it's the duration). You need to either call it with 'normal' as the duration, like this:

.animate({left: '+=100'}, 'normal', 'swing', doThis)

Or use the .animate(options, properties) version, like this:

.animate({left: '+=100'}, { easing: 'swing', complete: doThis })
Nick Craver
yup, i thought jQuery is said to have really good spec and documentation... but it is not very clear in this regard... maybe it is just relatively speaking, as compared to other js frameworks.
動靜能量
also, "normal" doesn't seem to be an official value (not in spec and not in code). We can pass in "weird" and it is still the default and the same as "normal"...
動靜能量
@Jian - There's actually been some discussion around `"normal"`, and actually jQuery UI breaks this because someone decided to break it, a change many are hoping gets reversed...jQuery UI shouldn't be breaking jQuery Core's behavior, especially when the documentation explicitly uses it. There are a few bugs opened on it, [here](http://dev.jqueryui.com/ticket/5456) and [here](http://dev.jqueryui.com/ticket/5474)
Nick Craver
A: 

even though I am still not so sure about the API spec, these are some viable solutions:

1) supply 400, "swing", doThis, since 400 seems to be the default duration (look for fast: in the jquery code and you can see fast is 600, slow is 200 as in the spec, and _default is 400.

2) supply undefined, "swing", doThis and it works. Supply null, "swing", doThis and it works too. Although maybe it is not good to depend on this method if it is not documented this way. undefined is the really way to go if argument is omitted but sometimes people say use null even though it is not officially correct.

3) just use {easing: "swing"} and that's the official way to skip the duration and provide a easing method. if callback is needed, then use {easing: "swing", complete: doThis}

Solution 3 seems to be the best, as it doesn't use what the vague part of the spec and go totally with the clearer part of the spec.

動靜能量