Moved readyList check.
[jquery.git] / src / core.js
1 // Define a local copy of jQuery
2 var jQuery = function( selector, context ) {
3                 // The jQuery object is actually just the init constructor 'enhanced'
4                 return new jQuery.fn.init( selector, context );
5         },
6
7         // Map over jQuery in case of overwrite
8         _jQuery = window.jQuery,
9
10         // Map over the $ in case of overwrite
11         _$ = window.$,
12
13         // Use the correct document accordingly with window argument (sandbox)
14         document = window.document,
15
16         // A central reference to the root jQuery(document)
17         rootjQuery,
18
19         // A simple way to check for HTML strings or ID strings
20         // (both of which we optimize for)
21         quickExpr = /^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/,
22
23         // Is it a simple selector
24         isSimple = /^.[^:#\[\.,]*$/,
25
26         // Check if a string has a non-whitespace character in it
27         rnotwhite = /\S/,
28
29         // Used for trimming whitespace
30         rtrim = /^(\s|\u00A0)+|(\s|\u00A0)+$/g,
31
32         // Match a standalone tag
33         rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/,
34
35         // Keep a UserAgent string for use with jQuery.browser
36         userAgent = navigator.userAgent.toLowerCase(),
37         
38         // Has the ready events already been bound?
39         readyBound = false,
40         
41         // The functions to execute on DOM ready
42         readyList = [],
43
44         // The ready event handler
45         DOMContentLoaded,
46
47         // Save a reference to some core methods
48         toString = Object.prototype.toString,
49         hasOwnProperty = Object.prototype.hasOwnProperty,
50         push = Array.prototype.push,
51         slice = Array.prototype.slice,
52         indexOf = Array.prototype.indexOf;
53
54 jQuery.fn = jQuery.prototype = {
55         init: function( selector, context ) {
56                 var match, elem, ret, doc, parent;
57
58                 // Handle $(""), $(null), or $(undefined)
59                 if ( !selector ) {
60                         return this;
61                 }
62
63                 // Handle $(DOMElement)
64                 if ( selector.nodeType ) {
65                         this.context = this[0] = selector;
66                         this.length = 1;
67                         return this;
68                 }
69
70                 // Handle HTML strings
71                 if ( typeof selector === "string" ) {
72                         // Are we dealing with HTML string or an ID?
73                         match = quickExpr.exec( selector );
74
75                         // Verify a match, and that no context was specified for #id
76                         if ( match && (match[1] || !context) ) {
77
78                                 // HANDLE: $(html) -> $(array)
79                                 if ( match[1] ) {
80                                         doc = (context ? context.ownerDocument || context : document);
81
82                                         // If a single string is passed in and it's a single tag
83                                         // just do a createElement and skip the rest
84                                         ret = rsingleTag.exec( selector );
85
86                                         if ( ret ) {
87                                                 selector = [ doc.createElement( ret[1] ) ];
88
89                                         } else {
90                                                 ret = buildFragment( [ match[1] ], [ doc ] );
91                                                 parent = ret.cacheable ? ret.fragment.cloneNode(true) : ret.fragment;
92                                                 selector = [];
93
94                                                 while ( parent.firstChild ) {
95                                                         selector.push( parent.removeChild( parent.firstChild ) );
96                                                 }
97                                         }
98
99                                 // HANDLE: $("#id")
100                                 } else {
101                                         elem = document.getElementById( match[2] );
102
103                                         if ( elem ) {
104                                                 // Handle the case where IE and Opera return items
105                                                 // by name instead of ID
106                                                 if ( elem.id !== match[2] ) {
107                                                         return rootjQuery.find( selector );
108                                                 }
109
110                                                 // Otherwise, we inject the element directly into the jQuery object
111                                                 this.length = 1;
112                                                 this[0] = elem;
113                                         }
114
115                                         this.context = document;
116                                         this.selector = selector;
117                                         return this;
118                                 }
119
120                         // HANDLE: $("TAG")
121                         } else if ( !context && /^\w+$/.test( selector ) ) {
122                                 this.selector = selector;
123                                 this.context = document;
124                                 selector = document.getElementsByTagName( selector );
125
126                         // HANDLE: $(expr, $(...))
127                         } else if ( !context || context.jquery ) {
128                                 return (context || rootjQuery).find( selector );
129
130                         // HANDLE: $(expr, context)
131                         // (which is just equivalent to: $(context).find(expr)
132                         } else {
133                                 return jQuery( context ).find( selector );
134                         }
135
136                 // HANDLE: $(function)
137                 // Shortcut for document ready
138                 } else if ( jQuery.isFunction( selector ) ) {
139                         return rootjQuery.ready( selector );
140                 }
141
142                 if (selector.selector !== undefined) {
143                         this.selector = selector.selector;
144                         this.context = selector.context;
145                 }
146
147                 return jQuery.isArray( selector ) ?
148                         this.setArray( selector ) :
149                         jQuery.makeArray( selector, this );
150         },
151
152         // Start with an empty selector
153         selector: "",
154
155         // The current version of jQuery being used
156         jquery: "@VERSION",
157
158         // The default length of a jQuery object is 0
159         length: 0,
160
161         // The number of elements contained in the matched element set
162         size: function() {
163                 return this.length;
164         },
165
166         toArray: function(){
167                 return slice.call( this, 0 );
168         },
169
170         // Get the Nth element in the matched element set OR
171         // Get the whole matched element set as a clean array
172         get: function( num ) {
173                 return num == null ?
174
175                         // Return a 'clean' array
176                         this.toArray() :
177
178                         // Return just the object
179                         ( num < 0 ? this.slice(num)[ 0 ] : this[ num ] );
180         },
181
182         // Take an array of elements and push it onto the stack
183         // (returning the new matched element set)
184         pushStack: function( elems, name, selector ) {
185                 // Build a new jQuery matched element set
186                 var ret = jQuery( elems || null );
187
188                 // Add the old object onto the stack (as a reference)
189                 ret.prevObject = this;
190
191                 ret.context = this.context;
192
193                 if ( name === "find" ) {
194                         ret.selector = this.selector + (this.selector ? " " : "") + selector;
195                 } else if ( name ) {
196                         ret.selector = this.selector + "." + name + "(" + selector + ")";
197                 }
198
199                 // Return the newly-formed element set
200                 return ret;
201         },
202
203         // Force the current matched set of elements to become
204         // the specified array of elements (destroying the stack in the process)
205         // You should use pushStack() in order to do this, but maintain the stack
206         setArray: function( elems ) {
207                 // Resetting the length to 0, then using the native Array push
208                 // is a super-fast way to populate an object with array-like properties
209                 this.length = 0;
210                 push.apply( this, elems );
211
212                 return this;
213         },
214
215         // Execute a callback for every element in the matched set.
216         // (You can seed the arguments with an array of args, but this is
217         // only used internally.)
218         each: function( callback, args ) {
219                 return jQuery.each( this, callback, args );
220         },
221         
222         ready: function( fn ) {
223                 // Attach the listeners
224                 jQuery.bindReady();
225
226                 // If the DOM is already ready
227                 if ( jQuery.isReady ) {
228                         // Execute the function immediately
229                         fn.call( document, jQuery );
230
231                 // Otherwise, remember the function for later
232                 } else if ( readyList ) {
233                         // Add the function to the wait list
234                         readyList.push( fn );
235                 }
236
237                 return this;
238         },
239         
240         eq: function( i ) {
241                 return i === -1 ?
242                         this.slice( i ) :
243                         this.slice( i, +i + 1 );
244         },
245
246         first: function() {
247                 return this.eq( 0 );
248         },
249
250         last: function() {
251                 return this.eq( -1 );
252         },
253
254         slice: function() {
255                 return this.pushStack( slice.apply( this, arguments ),
256                         "slice", slice.call(arguments).join(",") );
257         },
258
259         map: function( callback ) {
260                 return this.pushStack( jQuery.map(this, function(elem, i){
261                         return callback.call( elem, i, elem );
262                 }));
263         },
264         
265         end: function() {
266                 return this.prevObject || jQuery(null);
267         },
268
269         // For internal use only.
270         // Behaves like an Array's method, not like a jQuery method.
271         push: push,
272         sort: [].sort,
273         splice: [].splice
274 };
275
276 // Give the init function the jQuery prototype for later instantiation
277 jQuery.fn.init.prototype = jQuery.fn;
278
279 jQuery.extend = jQuery.fn.extend = function() {
280         // copy reference to target object
281         var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options, name, src, copy;
282
283         // Handle a deep copy situation
284         if ( typeof target === "boolean" ) {
285                 deep = target;
286                 target = arguments[1] || {};
287                 // skip the boolean and the target
288                 i = 2;
289         }
290
291         // Handle case when target is a string or something (possible in deep copy)
292         if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
293                 target = {};
294         }
295
296         // extend jQuery itself if only one argument is passed
297         if ( length === i ) {
298                 target = this;
299                 --i;
300         }
301
302         for ( ; i < length; i++ ) {
303                 // Only deal with non-null/undefined values
304                 if ( (options = arguments[ i ]) != null ) {
305                         // Extend the base object
306                         for ( name in options ) {
307                                 src = target[ name ];
308                                 copy = options[ name ];
309
310                                 // Prevent never-ending loop
311                                 if ( target === copy ) {
312                                         continue;
313                                 }
314
315                                 // Recurse if we're merging object literal values
316                                 if ( deep && copy && jQuery.isPlainObject(copy) ) {
317                                         // Don't extend not object literals
318                                         var clone = src && jQuery.isPlainObject(src) ? src : {};
319
320                                         // Never move original objects, clone them
321                                         target[ name ] = jQuery.extend( deep, clone, copy );
322
323                                 // Don't bring in undefined values
324                                 } else if ( copy !== undefined ) {
325                                         target[ name ] = copy;
326                                 }
327                         }
328                 }
329         }
330
331         // Return the modified object
332         return target;
333 };
334
335 jQuery.extend({
336         noConflict: function( deep ) {
337                 window.$ = _$;
338
339                 if ( deep ) {
340                         window.jQuery = _jQuery;
341                 }
342
343                 return jQuery;
344         },
345         
346         // Is the DOM ready to be used? Set to true once it occurs.
347         isReady: false,
348         
349         // Handle when the DOM is ready
350         ready: function() {
351                 // Make sure that the DOM is not already loaded
352                 if ( !jQuery.isReady ) {
353                         // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
354                         if ( !document.body ) {
355                                 return setTimeout( jQuery.ready, 13 );
356                         }
357
358                         // Remember that the DOM is ready
359                         jQuery.isReady = true;
360
361                         // If there are functions bound, to execute
362                         if ( readyList ) {
363                                 // Execute all of them
364                                 var fn, i = 0;
365                                 while ( (fn = readyList[ i++ ]) ) {
366                                         fn.call( document, jQuery );
367                                 }
368
369                                 // Reset the list of functions
370                                 readyList = null;
371                         }
372
373                         // Trigger any bound ready events
374                         if ( jQuery.fn.triggerHandler ) {
375                                 jQuery( document ).triggerHandler( "ready" );
376                         }
377                 }
378         },
379         
380         bindReady: function() {
381                 if ( readyBound ) { return; }
382                 readyBound = true;
383
384                 // Catch cases where $(document).ready() is called after the
385                 // browser event has already occurred.
386                 if ( document.readyState === "complete" ) {
387                         return jQuery.ready();
388                 }
389
390                 // Mozilla, Opera and webkit nightlies currently support this event
391                 if ( document.addEventListener ) {
392                         // Use the handy event callback
393                         document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
394                         
395                         // A fallback to window.onload, that will always work
396                         window.addEventListener( "load", jQuery.ready, false );
397
398                 // If IE event model is used
399                 } else if ( document.attachEvent ) {
400                         // ensure firing before onload,
401                         // maybe late but safe also for iframes
402                         document.attachEvent("onreadystatechange", DOMContentLoaded);
403                         
404                         // A fallback to window.onload, that will always work
405                         window.attachEvent( "onload", jQuery.ready );
406
407                         // If IE and not a frame
408                         // continually check to see if the document is ready
409                         var toplevel = false;
410
411                         try {
412                                 toplevel = window.frameElement == null;
413                         } catch(e){}
414
415                         if ( document.documentElement.doScroll && toplevel ) {
416                                 doScrollCheck();
417                         }
418                 }
419         },
420
421         // See test/unit/core.js for details concerning isFunction.
422         // Since version 1.3, DOM methods and functions like alert
423         // aren't supported. They return false on IE (#2968).
424         isFunction: function( obj ) {
425                 return toString.call(obj) === "[object Function]";
426         },
427
428         isArray: function( obj ) {
429                 return toString.call(obj) === "[object Array]";
430         },
431
432         isPlainObject: function( obj ) {
433                 if ( toString.call(obj) !== "[object Object]" || typeof obj.nodeType === "number" ) {
434                         return false;
435                 }
436                 
437                 // not own constructor property must be Object
438                 if ( obj.constructor
439                         && !hasOwnProperty.call(obj, "constructor")
440                         && !hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf") ) {
441                         return false;
442                 }
443                 
444                 //own properties are iterated firstly,
445                 //so to speed up, we can test last one if it is own or not
446         
447                 var key;
448                 for ( key in obj ) {}
449                 
450                 return key === undefined || hasOwnProperty.call( obj, key );
451         },
452
453         isEmptyObject: function( obj ) {
454                 for ( var name in obj ) {
455                         return false;
456                 }
457                 return true;
458         },
459
460         // Evalulates a script in a global context
461         globalEval: function( data ) {
462                 if ( data && rnotwhite.test(data) ) {
463                         // Inspired by code by Andrea Giammarchi
464                         // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
465                         var head = document.getElementsByTagName("head")[0] || document.documentElement,
466                                 script = document.createElement("script");
467
468                         script.type = "text/javascript";
469
470                         if ( jQuery.support.scriptEval ) {
471                                 script.appendChild( document.createTextNode( data ) );
472                         } else {
473                                 script.text = data;
474                         }
475
476                         // Use insertBefore instead of appendChild to circumvent an IE6 bug.
477                         // This arises when a base node is used (#2709).
478                         head.insertBefore( script, head.firstChild );
479                         head.removeChild( script );
480                 }
481         },
482
483         nodeName: function( elem, name ) {
484                 return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
485         },
486
487         // args is for internal usage only
488         each: function( object, callback, args ) {
489                 var name, i = 0,
490                         length = object.length,
491                         isObj = length === undefined || jQuery.isFunction(object);
492
493                 if ( args ) {
494                         if ( isObj ) {
495                                 for ( name in object ) {
496                                         if ( callback.apply( object[ name ], args ) === false ) {
497                                                 break;
498                                         }
499                                 }
500                         } else {
501                                 for ( ; i < length; ) {
502                                         if ( callback.apply( object[ i++ ], args ) === false ) {
503                                                 break;
504                                         }
505                                 }
506                         }
507
508                 // A special, fast, case for the most common use of each
509                 } else {
510                         if ( isObj ) {
511                                 for ( name in object ) {
512                                         if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
513                                                 break;
514                                         }
515                                 }
516                         } else {
517                                 for ( var value = object[0];
518                                         i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {}
519                         }
520                 }
521
522                 return object;
523         },
524
525         trim: function( text ) {
526                 return (text || "").replace( rtrim, "" );
527         },
528
529         // results is for internal usage only
530         makeArray: function( array, results ) {
531                 var ret = results || [];
532
533                 if ( array != null ) {
534                         // The window, strings (and functions) also have 'length'
535                         // The extra typeof function check is to prevent crashes
536                         // in Safari 2 (See: #3039)
537                         if ( array.length == null || typeof array === "string" || jQuery.isFunction(array) || (typeof array !== "function" && array.setInterval) ) {
538                                 push.call( ret, array );
539                         } else {
540                                 jQuery.merge( ret, array );
541                         }
542                 }
543
544                 return ret;
545         },
546
547         inArray: function( elem, array ) {
548                 if ( array.indexOf ) {
549                         return array.indexOf( elem );
550                 }
551
552                 for ( var i = 0, length = array.length; i < length; i++ ) {
553                         if ( array[ i ] === elem ) {
554                                 return i;
555                         }
556                 }
557
558                 return -1;
559         },
560
561         merge: function( first, second ) {
562                 var i = first.length, j = 0;
563
564                 if ( typeof second.length === "number" ) {
565                         for ( var l = second.length; j < l; j++ ) {
566                                 first[ i++ ] = second[ j ];
567                         }
568                 } else {
569                         while ( second[j] !== undefined ) {
570                                 first[ i++ ] = second[ j++ ];
571                         }
572                 }
573
574                 first.length = i;
575
576                 return first;
577         },
578
579         grep: function( elems, callback, inv ) {
580                 var ret = [];
581
582                 // Go through the array, only saving the items
583                 // that pass the validator function
584                 for ( var i = 0, length = elems.length; i < length; i++ ) {
585                         if ( !inv !== !callback( elems[ i ], i ) ) {
586                                 ret.push( elems[ i ] );
587                         }
588                 }
589
590                 return ret;
591         },
592
593         // arg is for internal usage only
594         map: function( elems, callback, arg ) {
595                 var ret = [], value;
596
597                 // Go through the array, translating each of the items to their
598                 // new value (or values).
599                 for ( var i = 0, length = elems.length; i < length; i++ ) {
600                         value = callback( elems[ i ], i, arg );
601
602                         if ( value != null ) {
603                                 ret[ ret.length ] = value;
604                         }
605                 }
606
607                 return ret.concat.apply( [], ret );
608         },
609
610         // Use of jQuery.browser is frowned upon.
611         // More details: http://docs.jquery.com/Utilities/jQuery.browser
612         browser: {
613                 version: (/.*?(?:firefox|safari|opera|msie)[\/ ]([\d.]+)/.exec(userAgent) || [0,'0'])[1],
614                 safari: /safari/.test( userAgent ),
615                 opera: /opera/.test( userAgent ),
616                 msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
617                 firefox: /firefox/.test( userAgent )
618         }
619 });
620
621 // Deprecated
622 jQuery.browser.mozilla = /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent );
623
624 if ( indexOf ) {
625         jQuery.inArray = function( elem, array ) {
626                 return indexOf.call( array, elem );
627         };
628 }
629
630 // All jQuery objects should point back to these
631 rootjQuery = jQuery(document);
632
633 // Cleanup functions for the document ready method
634 if ( document.addEventListener ) {
635         DOMContentLoaded = function() {
636                 document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
637                 jQuery.ready();
638         };
639
640 } else if ( document.attachEvent ) {
641         DOMContentLoaded = function() {
642                 // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
643                 if ( document.readyState === "complete" ) {
644                         document.detachEvent( "onreadystatechange", DOMContentLoaded );
645                         jQuery.ready();
646                 }
647         };
648 }
649
650 // The DOM ready check for Internet Explorer
651 function doScrollCheck() {
652         if ( jQuery.isReady ) {
653                 return;
654         }
655
656         try {
657                 // If IE is used, use the trick by Diego Perini
658                 // http://javascript.nwbox.com/IEContentLoaded/
659                 document.documentElement.doScroll("left");
660         } catch( error ) {
661                 setTimeout( doScrollCheck, 1 );
662                 return;
663         }
664
665         // and execute any waiting functions
666         jQuery.ready();
667 }
668
669 if ( indexOf ) {
670         jQuery.inArray = function( elem, array ) {
671                 return indexOf.call( array, elem );
672         };
673 }
674
675 function evalScript( i, elem ) {
676         if ( elem.src ) {
677                 jQuery.ajax({
678                         url: elem.src,
679                         async: false,
680                         dataType: "script"
681                 });
682         } else {
683                 jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );
684         }
685
686         if ( elem.parentNode ) {
687                 elem.parentNode.removeChild( elem );
688         }
689 }
690
691 // Mutifunctional method to get and set values to a collection
692 // The value/s can be optionally by executed if its a function
693 function access( elems, key, value, exec, fn ) {
694         var length = elems.length;
695         
696         // Setting many attributes
697         if ( typeof key === "object" ) {
698                 for ( var k in key ) {
699                         access( elems, k, key[k], exec, fn );
700                 }
701                 return elems;
702         }
703         
704         // Setting one attribute
705         if ( value !== undefined ) {
706                 // Optionally, function values get executed if exec is true
707                 exec = exec && jQuery.isFunction(value);
708                 
709                 for ( var i = 0; i < length; i++ ) {
710                         fn( elems[i], key, exec ? value.call( elems[i], i ) : value );
711                 }
712                 
713                 return elems;
714         }
715         
716         // Getting an attribute
717         return length ? fn( elems[0], key ) : null;
718 }
719
720 function now() {
721         return (new Date).getTime();
722 }