Fix for #1214, #1216, #1234 (problem with animations). In a nutshell, the callback...
[jquery.git] / src / fx / fx.js
1 jQuery.fn.extend({
2
3         /**
4          * Displays each of the set of matched elements if they are hidden.
5          *
6          * @example $("p").show()
7          * @before <p style="display: none">Hello</p>
8          * @result [ <p style="display: block">Hello</p> ]
9          *
10          * @name show
11          * @type jQuery
12          * @cat Effects
13          */
14         
15         /**
16          * Show all matched elements using a graceful animation and firing an
17          * optional callback after completion.
18          *
19          * The height, width, and opacity of each of the matched elements 
20          * are changed dynamically according to the specified speed.
21          *
22          * @example $("p").show("slow");
23          *
24          * @example $("p").show("slow",function(){
25          *   alert("Animation Done.");
26          * });
27          *
28          * @name show
29          * @type jQuery
30          * @param String|Number speed A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
31          * @param Function callback (optional) A function to be executed whenever the animation completes.
32          * @cat Effects
33          * @see hide(String|Number,Function)
34          */
35         show: function(speed,callback){
36                 return speed ?
37                         this.animate({
38                                 height: "show", width: "show", opacity: "show"
39                         }, speed, callback) :
40                         
41                         this.filter(":hidden").each(function(){
42                                 this.style.display = this.oldblock ? this.oldblock : "";
43                                 if ( jQuery.css(this,"display") == "none" )
44                                         this.style.display = "block";
45                         }).end();
46         },
47         
48         /**
49          * Hides each of the set of matched elements if they are shown.
50          *
51          * @example $("p").hide()
52          * @before <p>Hello</p>
53          * @result [ <p style="display: none">Hello</p> ]
54          *
55          * @name hide
56          * @type jQuery
57          * @cat Effects
58          */
59         
60         /**
61          * Hide all matched elements using a graceful animation and firing an
62          * optional callback after completion.
63          *
64          * The height, width, and opacity of each of the matched elements 
65          * are changed dynamically according to the specified speed.
66          *
67          * @example $("p").hide("slow");
68          *
69          * @example $("p").hide("slow",function(){
70          *   alert("Animation Done.");
71          * });
72          *
73          * @name hide
74          * @type jQuery
75          * @param String|Number speed A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
76          * @param Function callback (optional) A function to be executed whenever the animation completes.
77          * @cat Effects
78          * @see show(String|Number,Function)
79          */
80         hide: function(speed,callback){
81                 return speed ?
82                         this.animate({
83                                 height: "hide", width: "hide", opacity: "hide"
84                         }, speed, callback) :
85                         
86                         this.filter(":visible").each(function(){
87                                 this.oldblock = this.oldblock || jQuery.css(this,"display");
88                                 if ( this.oldblock == "none" )
89                                         this.oldblock = "block";
90                                 this.style.display = "none";
91                         }).end();
92         },
93
94         // Save the old toggle function
95         _toggle: jQuery.fn.toggle,
96         
97         /**
98          * Toggles each of the set of matched elements. If they are shown,
99          * toggle makes them hidden. If they are hidden, toggle
100          * makes them shown.
101          *
102          * @example $("p").toggle()
103          * @before <p>Hello</p><p style="display: none">Hello Again</p>
104          * @result [ <p style="display: none">Hello</p>, <p style="display: block">Hello Again</p> ]
105          *
106          * @name toggle
107          * @type jQuery
108          * @cat Effects
109          */
110         toggle: function( fn, fn2 ){
111                 return jQuery.isFunction(fn) && jQuery.isFunction(fn2) ?
112                         this._toggle( fn, fn2 ) :
113                         this.animate({
114                                 height: "toggle", width: "toggle", opacity: "toggle"
115                         }, fn, fn2);
116         },
117         
118         /**
119          * Reveal all matched elements by adjusting their height and firing an
120          * optional callback after completion.
121          *
122          * Only the height is adjusted for this animation, causing all matched
123          * elements to be revealed in a "sliding" manner.
124          *
125          * @example $("p").slideDown("slow");
126          *
127          * @example $("p").slideDown("slow",function(){
128          *   alert("Animation Done.");
129          * });
130          *
131          * @name slideDown
132          * @type jQuery
133          * @param String|Number speed (optional) A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
134          * @param Function callback (optional) A function to be executed whenever the animation completes.
135          * @cat Effects
136          * @see slideUp(String|Number,Function)
137          * @see slideToggle(String|Number,Function)
138          */
139         slideDown: function(speed,callback){
140                 return this.animate({height: "show"}, speed, callback);
141         },
142         
143         /**
144          * Hide all matched elements by adjusting their height and firing an
145          * optional callback after completion.
146          *
147          * Only the height is adjusted for this animation, causing all matched
148          * elements to be hidden in a "sliding" manner.
149          *
150          * @example $("p").slideUp("slow");
151          *
152          * @example $("p").slideUp("slow",function(){
153          *   alert("Animation Done.");
154          * });
155          *
156          * @name slideUp
157          * @type jQuery
158          * @param String|Number speed (optional) A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
159          * @param Function callback (optional) A function to be executed whenever the animation completes.
160          * @cat Effects
161          * @see slideDown(String|Number,Function)
162          * @see slideToggle(String|Number,Function)
163          */
164         slideUp: function(speed,callback){
165                 return this.animate({height: "hide"}, speed, callback);
166         },
167
168         /**
169          * Toggle the visibility of all matched elements by adjusting their height and firing an
170          * optional callback after completion.
171          *
172          * Only the height is adjusted for this animation, causing all matched
173          * elements to be hidden in a "sliding" manner.
174          *
175          * @example $("p").slideToggle("slow");
176          *
177          * @example $("p").slideToggle("slow",function(){
178          *   alert("Animation Done.");
179          * });
180          *
181          * @name slideToggle
182          * @type jQuery
183          * @param String|Number speed (optional) A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
184          * @param Function callback (optional) A function to be executed whenever the animation completes.
185          * @cat Effects
186          * @see slideDown(String|Number,Function)
187          * @see slideUp(String|Number,Function)
188          */
189         slideToggle: function(speed, callback){
190                 return this.animate({height: "toggle"}, speed, callback);
191         },
192         
193         /**
194          * Fade in all matched elements by adjusting their opacity and firing an
195          * optional callback after completion.
196          *
197          * Only the opacity is adjusted for this animation, meaning that
198          * all of the matched elements should already have some form of height
199          * and width associated with them.
200          *
201          * @example $("p").fadeIn("slow");
202          *
203          * @example $("p").fadeIn("slow",function(){
204          *   alert("Animation Done.");
205          * });
206          *
207          * @name fadeIn
208          * @type jQuery
209          * @param String|Number speed (optional) A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
210          * @param Function callback (optional) A function to be executed whenever the animation completes.
211          * @cat Effects
212          * @see fadeOut(String|Number,Function)
213          * @see fadeTo(String|Number,Number,Function)
214          */
215         fadeIn: function(speed, callback){
216                 return this.animate({opacity: "show"}, speed, callback);
217         },
218         
219         /**
220          * Fade out all matched elements by adjusting their opacity and firing an
221          * optional callback after completion.
222          *
223          * Only the opacity is adjusted for this animation, meaning that
224          * all of the matched elements should already have some form of height
225          * and width associated with them.
226          *
227          * @example $("p").fadeOut("slow");
228          *
229          * @example $("p").fadeOut("slow",function(){
230          *   alert("Animation Done.");
231          * });
232          *
233          * @name fadeOut
234          * @type jQuery
235          * @param String|Number speed (optional) A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
236          * @param Function callback (optional) A function to be executed whenever the animation completes.
237          * @cat Effects
238          * @see fadeIn(String|Number,Function)
239          * @see fadeTo(String|Number,Number,Function)
240          */
241         fadeOut: function(speed, callback){
242                 return this.animate({opacity: "hide"}, speed, callback);
243         },
244         
245         /**
246          * Fade the opacity of all matched elements to a specified opacity and firing an
247          * optional callback after completion.
248          *
249          * Only the opacity is adjusted for this animation, meaning that
250          * all of the matched elements should already have some form of height
251          * and width associated with them.
252          *
253          * @example $("p").fadeTo("slow", 0.5);
254          *
255          * @example $("p").fadeTo("slow", 0.5, function(){
256          *   alert("Animation Done.");
257          * });
258          *
259          * @name fadeTo
260          * @type jQuery
261          * @param String|Number speed A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
262          * @param Number opacity The opacity to fade to (a number from 0 to 1).
263          * @param Function callback (optional) A function to be executed whenever the animation completes.
264          * @cat Effects
265          * @see fadeIn(String|Number,Function)
266          * @see fadeOut(String|Number,Function)
267          */
268         fadeTo: function(speed,to,callback){
269                 return this.animate({opacity: to}, speed, callback);
270         },
271         
272         /**
273          * A function for making your own, custom animations. The key aspect of
274          * this function is the object of style properties that will be animated,
275          * and to what end. Each key within the object represents a style property
276          * that will also be animated (for example: "height", "top", or "opacity").
277          *
278          * Note that properties should be specified using camel case
279          * eg. marginLeft instead of margin-left.
280          *
281          * The value associated with the key represents to what end the property
282          * will be animated. If a number is provided as the value, then the style
283          * property will be transitioned from its current state to that new number.
284          * Otherwise if the string "hide", "show", or "toggle" is provided, a default
285          * animation will be constructed for that property.
286          *
287          * @example $("p").animate({
288          *   height: 'toggle', opacity: 'toggle'
289          * }, "slow");
290          *
291          * @example $("p").animate({
292          *   left: 50, opacity: 'show'
293          * }, 500);
294          *
295          * @example $("p").animate({
296          *   opacity: 'show'
297          * }, "slow", "easein");
298          * @desc An example of using an 'easing' function to provide a different style of animation. This will only work if you have a plugin that provides this easing function (Only "swing" and "linear" are provided by default, with jQuery).
299          *
300          * @name animate
301          * @type jQuery
302          * @param Hash params A set of style attributes that you wish to animate, and to what end.
303          * @param String|Number speed (optional) A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
304          * @param String easing (optional) The name of the easing effect that you want to use (e.g. "swing" or "linear"). Defaults to "swing".
305          * @param Function callback (optional) A function to be executed whenever the animation completes.
306          * @cat Effects
307          */
308         animate: function( prop, speed, easing, callback ) {
309                 return this.queue(function(){
310                         var hidden = jQuery(this).is(":hidden"),
311                                 opt = jQuery.speed(speed, easing, callback),
312                                 self = this;
313                         
314                         for ( var p in prop )
315                                 if ( prop[p] == "hide" && hidden || prop[p] == "show" && !hidden )
316                                         return jQuery.isFunction(opt.complete) && opt.complete.apply(this);
317                 
318                         this.curAnim = jQuery.extend({}, prop);
319                         
320                         jQuery.each( prop, function(name, val){
321                                 var e = new jQuery.fx( self, opt, name );
322                                 if ( val.constructor == Number )
323                                         e.custom( e.cur(), val );
324                                 else
325                                         e[ val == "toggle" ? hidden ? "show" : "hide" : val ]( prop );
326                         });
327                 });
328         },
329         
330         /**
331          *
332          * @private
333          */
334         queue: function(type,fn){
335                 if ( !fn ) {
336                         fn = type;
337                         type = "fx";
338                 }
339         
340                 return this.each(function(){
341                         if ( !this.queue )
342                                 this.queue = {};
343         
344                         if ( !this.queue[type] )
345                                 this.queue[type] = [];
346         
347                         this.queue[type].push( fn );
348                 
349                         if ( this.queue[type].length == 1 )
350                                 fn.apply(this);
351                 });
352         }
353
354 });
355
356 jQuery.extend({
357         
358         speed: function(speed, easing, fn) {
359                 var opt = speed && speed.constructor == Object ? speed : {
360                         complete: fn || !fn && easing || 
361                                 jQuery.isFunction( speed ) && speed,
362                         duration: speed,
363                         easing: fn && easing || easing && easing.constructor != Function && easing || "swing"
364                 };
365
366                 opt.duration = (opt.duration && opt.duration.constructor == Number ? 
367                         opt.duration : 
368                         { slow: 600, fast: 200 }[opt.duration]) || 400;
369         
370                 // Queueing
371                 opt.old = opt.complete;
372                 opt.complete = function(){
373                         jQuery.dequeue(this, "fx");
374                         if ( jQuery.isFunction( opt.old ) )
375                                 opt.old.apply( this );
376                 };
377         
378                 return opt;
379         },
380         
381         easing: {
382                 linear: function( p, n, firstNum, diff ) {
383                         return firstNum + diff * p;
384                 },
385                 swing: function( p, n, firstNum, diff ) {
386                         return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum;
387                 }
388         },
389         
390         queue: {},
391         
392         dequeue: function(elem,type){
393                 type = type || "fx";
394         
395                 if ( elem.queue && elem.queue[type] ) {
396                         // Remove self
397                         elem.queue[type].shift();
398         
399                         // Get next function
400                         var f = elem.queue[type][0];
401                 
402                         if ( f ) f.apply( elem );
403                 }
404         },
405
406         timers: [],
407
408         /*
409          * I originally wrote fx() as a clone of moo.fx and in the process
410          * of making it small in size the code became illegible to sane
411          * people. You've been warned.
412          */
413         
414         fx: function( elem, options, prop ){
415
416                 var z = this;
417
418                 // The styles
419                 var y = elem.style;
420                 
421                 if ( prop == "height" || prop == "width" ) {
422                         // Store display property
423                         var oldDisplay = jQuery.css(elem, "display");
424
425                         // Make sure that nothing sneaks out
426                         var oldOverflow = y.overflow;
427                         y.overflow = "hidden";
428                 }
429
430                 // Simple function for setting a style value
431                 z.a = function(){
432                         if ( options.step )
433                                 options.step.apply( elem, [ z.now ] );
434
435                         if ( prop == "opacity" )
436                                 jQuery.attr(y, "opacity", z.now); // Let attr handle opacity
437                         else {
438                                 y[prop] = parseInt(z.now) + "px";
439                                 y.display = "block"; // Set display property to block for animation
440                         }
441                 };
442
443                 // Figure out the maximum number to run to
444                 z.max = function(){
445                         return parseFloat( jQuery.css(elem,prop) );
446                 };
447
448                 // Get the current size
449                 z.cur = function(){
450                         var r = parseFloat( jQuery.curCSS(elem, prop) );
451                         return r && r > -10000 ? r : z.max();
452                 };
453
454                 // Start an animation from one number to another
455                 z.custom = function(from,to){
456                         z.startTime = (new Date()).getTime();
457                         z.now = from;
458                         z.a();
459
460                         jQuery.timers.push(function(){
461                                 return z.step(from, to);
462                         });
463
464                         if ( jQuery.timers.length == 1 ) {
465                                 var timer = setInterval(function(){
466                                         var timers = jQuery.timers;
467                                         
468                                         for ( var i = 0; i < timers.length; i++ )
469                                                 if ( !timers[i]() )
470                                                         timers.splice(i--, 1);
471
472                                         if ( !timers.length )
473                                                 clearInterval( timer );
474                                 }, 13);
475                         }
476                 };
477
478                 // Simple 'show' function
479                 z.show = function(){
480                         if ( !elem.orig ) elem.orig = {};
481
482                         // Remember where we started, so that we can go back to it later
483                         elem.orig[prop] = jQuery.attr( elem.style, prop );
484
485                         options.show = true;
486
487                         // Begin the animation
488                         z.custom(0, this.cur());
489
490                         // Make sure that we start at a small width/height to avoid any
491                         // flash of content
492                         if ( prop != "opacity" )
493                                 y[prop] = "1px";
494                         
495                         // Start by showing the element
496                         jQuery(elem).show();
497                 };
498
499                 // Simple 'hide' function
500                 z.hide = function(){
501                         if ( !elem.orig ) elem.orig = {};
502
503                         // Remember where we started, so that we can go back to it later
504                         elem.orig[prop] = jQuery.attr( elem.style, prop );
505
506                         options.hide = true;
507
508                         // Begin the animation
509                         z.custom(this.cur(), 0);
510                 };
511
512                 // Each step of an animation
513                 z.step = function(firstNum, lastNum){
514                         var t = (new Date()).getTime();
515
516                         if (t > options.duration + z.startTime) {
517                                 z.now = lastNum;
518                                 z.a();
519
520                                 if (elem.curAnim) elem.curAnim[ prop ] = true;
521
522                                 var done = true;
523                                 for ( var i in elem.curAnim )
524                                         if ( elem.curAnim[i] !== true )
525                                                 done = false;
526
527                                 if ( done ) {
528                                         if ( oldDisplay != null ) {
529                                                 // Reset the overflow
530                                                 y.overflow = oldOverflow;
531                                         
532                                                 // Reset the display
533                                                 y.display = oldDisplay;
534                                                 if ( jQuery.css(elem, "display") == "none" )
535                                                         y.display = "block";
536                                         }
537
538                                         // Hide the element if the "hide" operation was done
539                                         if ( options.hide )
540                                                 y.display = "none";
541
542                                         // Reset the properties, if the item has been hidden or shown
543                                         if ( options.hide || options.show )
544                                                 for ( var p in elem.curAnim )
545                                                         jQuery.attr(y, p, elem.orig[p]);
546                                 }
547
548                                 // If a callback was provided, execute it
549                                 if ( done && jQuery.isFunction( options.complete ) )
550                                         // Execute the complete function
551                                         options.complete.apply( elem );
552
553                                 return false;
554                         } else {
555                                 var n = t - this.startTime;
556                                 // Figure out where in the animation we are and set the number
557                                 var p = n / options.duration;
558                                 
559                                 // Perform the easing function, defaults to swing
560                                 z.now = jQuery.easing[options.easing](p, n, firstNum, (lastNum-firstNum), options.duration);
561
562                                 // Perform the next step of the animation
563                                 z.a();
564                         }
565
566                         return true;
567                 };
568         
569         }
570 });