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