I am trying to imitate the jQuery animate() method to strip out the opacity style for unsupported browsers (Internet Explorer of course)!
However, I am struggling to imitate the parameters that the jQuery animate() method accepts.
According to the jQuery documentation:
.animate( properties [, duration] [, easing] [, complete] )
.animate( properties, options )
What I would like to know is how does the function know whether parameter 2 is the duration or the options…?
Notice the three arguments here:
$('#test').animate({opacity:0},200,function(){
$(this).hide();
});
But I can also execute the same function like this (notice the easing parameter):
$('#test').animate({opacity:0},200,'swing',function(){
$(this).hide();
});
How does the function know that the third parameter is a string, not a function?
Surely this is not done like so????
if(typeof parameter1=='string'){
// and so on
}
Yes, that is exactly how it is done.
From the jQuery source:
Can be rewritten to be more readable this way:
Update
If you want an easier way to take care of this logic for you, candy provides a neat Array helper called
persuade. This function allows you to pass in an array (orarguments) object with a list of types. You will be returned an array with the arguments organized by the types. It’s an easy way to deal with polymorphic parameters: