Switched jQuery() to represent jQuery([]) instead of jQuery(document).
[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         // Save a reference to some core methods
45         toString = Object.prototype.toString,
46         hasOwnProperty = Object.prototype.hasOwnProperty,
47         push = Array.prototype.push,
48         slice = Array.prototype.slice,
49         indexOf = Array.prototype.indexOf;
50
51 jQuery.fn = jQuery.prototype = {
52         init: function( selector, context ) {
53                 var match, elem, ret, doc;
54
55                 // Handle $(""), $(null), or $(undefined)
56                 if ( !selector ) {
57                         return this;
58                 }
59
60                 // Handle $(DOMElement)
61                 if ( selector.nodeType ) {
62                         this.context = this[0] = selector;
63                         this.length = 1;
64                         return this;
65                 }
66
67                 // Handle HTML strings
68                 if ( typeof selector === "string" ) {
69                         // Are we dealing with HTML string or an ID?
70                         match = quickExpr.exec( selector );
71
72                         // Verify a match, and that no context was specified for #id
73                         if ( match && (match[1] || !context) ) {
74
75                                 // HANDLE: $(html) -> $(array)
76                                 if ( match[1] ) {
77                                         doc = (context ? context.ownerDocument || context : document);
78
79                                         // If a single string is passed in and it's a single tag
80                                         // just do a createElement and skip the rest
81                                         ret = rsingleTag.exec( selector );
82
83                                         if ( ret ) {
84                                                 selector = [ doc.createElement( ret[1] ) ];
85
86                                         } else {
87                                                 ret = buildFragment( [ match[1] ], [ doc ] );
88                                                 selector = (ret.cacheable ? ret.fragment.cloneNode(true) : ret.fragment).childNodes;
89                                         }
90
91                                 // HANDLE: $("#id")
92                                 } else {
93                                         elem = document.getElementById( match[2] );
94
95                                         if ( elem ) {
96                                                 // Handle the case where IE and Opera return items
97                                                 // by name instead of ID
98                                                 if ( elem.id !== match[2] ) {
99                                                         return rootjQuery.find( selector );
100                                                 }
101
102                                                 // Otherwise, we inject the element directly into the jQuery object
103                                                 this.length = 1;
104                                                 this[0] = elem;
105                                         }
106
107                                         this.context = document;
108                                         this.selector = selector;
109                                         return this;
110                                 }
111
112                         // HANDLE: $("TAG")
113                         } else if ( !context && /^\w+$/.test( selector ) ) {
114                                 this.selector = selector;
115                                 this.context = document;
116                                 selector = document.getElementsByTagName( selector );
117
118                         // HANDLE: $(expr, $(...))
119                         } else if ( !context || context.jquery ) {
120                                 return (context || rootjQuery).find( selector );
121
122                         // HANDLE: $(expr, context)
123                         // (which is just equivalent to: $(context).find(expr)
124                         } else {
125                                 return jQuery( context ).find( selector );
126                         }
127
128                 // HANDLE: $(function)
129                 // Shortcut for document ready
130                 } else if ( jQuery.isFunction( selector ) ) {
131                         return rootjQuery.ready( selector );
132                 }
133
134                 if (selector.selector !== undefined) {
135                         this.selector = selector.selector;
136                         this.context = selector.context;
137                 }
138
139                 return jQuery.isArray( selector ) ?
140                         this.setArray( selector ) :
141                         jQuery.makeArray( selector, this );
142         },
143
144         // Start with an empty selector
145         selector: "",
146
147         // The current version of jQuery being used
148         jquery: "@VERSION",
149
150         // The default length of a jQuery object is 0
151         length: 0,
152
153         // The number of elements contained in the matched element set
154         size: function() {
155                 return this.length;
156         },
157
158         toArray: function(){
159                 return slice.call( this, 0 );
160         },
161
162         // Get the Nth element in the matched element set OR
163         // Get the whole matched element set as a clean array
164         get: function( num ) {
165                 return num == null ?
166
167                         // Return a 'clean' array
168                         this.toArray() :
169
170                         // Return just the object
171                         ( num < 0 ? this.slice(num)[ 0 ] : this[ num ] );
172         },
173
174         // Take an array of elements and push it onto the stack
175         // (returning the new matched element set)
176         pushStack: function( elems, name, selector ) {
177                 // Build a new jQuery matched element set
178                 var ret = jQuery( elems || null );
179
180                 // Add the old object onto the stack (as a reference)
181                 ret.prevObject = this;
182
183                 ret.context = this.context;
184
185                 if ( name === "find" ) {
186                         ret.selector = this.selector + (this.selector ? " " : "") + selector;
187                 } else if ( name ) {
188                         ret.selector = this.selector + "." + name + "(" + selector + ")";
189                 }
190
191                 // Return the newly-formed element set
192                 return ret;
193         },
194
195         // Force the current matched set of elements to become
196         // the specified array of elements (destroying the stack in the process)
197         // You should use pushStack() in order to do this, but maintain the stack
198         setArray: function( elems ) {
199                 // Resetting the length to 0, then using the native Array push
200                 // is a super-fast way to populate an object with array-like properties
201                 this.length = 0;
202                 push.apply( this, elems );
203
204                 return this;
205         },
206
207         // Execute a callback for every element in the matched set.
208         // (You can seed the arguments with an array of args, but this is
209         // only used internally.)
210         each: function( callback, args ) {
211                 return jQuery.each( this, callback, args );
212         },
213
214         // Determine the position of an element within
215         // the matched set of elements
216         index: function( elem ) {
217                 if ( !elem || typeof elem === "string" ) {
218                         return jQuery.inArray( this[0],
219                                 // If it receives a string, the selector is used
220                                 // If it receives nothing, the siblings are used
221                                 elem ? jQuery( elem ) : this.parent().children() );
222                 }
223                 // Locate the position of the desired element
224                 return jQuery.inArray(
225                         // If it receives a jQuery object, the first element is used
226                         elem.jquery ? elem[0] : elem, this );
227         },
228
229         is: function( selector ) {
230                 return !!selector && jQuery.filter( selector, this ).length > 0;
231         },
232         
233         ready: function( fn ) {
234                 // Attach the listeners
235                 jQuery.bindReady();
236
237                 // If the DOM is already ready
238                 if ( jQuery.isReady && !readyList ) {
239                         // Execute the function immediately
240                         fn.call( document, jQuery );
241
242                 // Otherwise, remember the function for later
243                 } else {
244                         // Add the function to the wait list
245                         readyList.push( fn );
246                 }
247
248                 return this;
249         },
250
251         // For internal use only.
252         // Behaves like an Array's method, not like a jQuery method.
253         push: push,
254         sort: [].sort,
255         splice: [].splice
256 };
257
258 // Give the init function the jQuery prototype for later instantiation
259 jQuery.fn.init.prototype = jQuery.fn;
260
261 jQuery.extend = jQuery.fn.extend = function() {
262         // copy reference to target object
263         var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options, name, src, copy;
264
265         // Handle a deep copy situation
266         if ( typeof target === "boolean" ) {
267                 deep = target;
268                 target = arguments[1] || {};
269                 // skip the boolean and the target
270                 i = 2;
271         }
272
273         // Handle case when target is a string or something (possible in deep copy)
274         if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
275                 target = {};
276         }
277
278         // extend jQuery itself if only one argument is passed
279         if ( length === i ) {
280                 target = this;
281                 --i;
282         }
283
284         for ( ; i < length; i++ ) {
285                 // Only deal with non-null/undefined values
286                 if ( (options = arguments[ i ]) != null ) {
287                         // Extend the base object
288                         for ( name in options ) {
289                                 src = target[ name ];
290                                 copy = options[ name ];
291
292                                 // Prevent never-ending loop
293                                 if ( target === copy ) {
294                                         continue;
295                                 }
296
297                                 // Recurse if we're merging object literal values
298                                 if ( deep && copy && jQuery.isPlainObject(copy) ) {
299                                         // Don't extend not object literals
300                                         var clone = src && jQuery.isPlainObject(src) ? src : {};
301
302                                         // Never move original objects, clone them
303                                         target[ name ] = jQuery.extend( deep, clone, copy );
304
305                                 // Don't bring in undefined values
306                                 } else if ( copy !== undefined ) {
307                                         target[ name ] = copy;
308                                 }
309                         }
310                 }
311         }
312
313         // Return the modified object
314         return target;
315 };
316
317 jQuery.extend({
318         noConflict: function( deep ) {
319                 window.$ = _$;
320
321                 if ( deep ) {
322                         window.jQuery = _jQuery;
323                 }
324
325                 return jQuery;
326         },
327         
328         // Is the DOM ready to be used? Set to true once it occurs.
329         isReady: false,
330         
331         // Handle when the DOM is ready
332         ready: function() {
333                 // Make sure that the DOM is not already loaded
334                 if ( !jQuery.isReady ) {
335                         if ( !document.body ) {
336                                 return setTimeout( jQuery.ready, 13 );
337                         }
338
339                         // Remember that the DOM is ready
340                         jQuery.isReady = true;
341
342                         // If there are functions bound, to execute
343                         if ( readyList ) {
344                                 // Execute all of them
345                                 var fn, i = 0;
346                                 while ( (fn = readyList[ i++ ]) ) {
347                                         fn.call( document, jQuery );
348                                 }
349
350                                 // Reset the list of functions
351                                 readyList = null;
352                         }
353
354                         // Trigger any bound ready events
355                         if ( jQuery.fn.triggerHandler ) {
356                                 jQuery( document ).triggerHandler( "ready" );
357                         }
358                 }
359         },
360         
361         bindReady: function() {
362                 if ( readyBound ) { return; }
363                 readyBound = true;
364
365                 // Catch cases where $(document).ready() is called after the
366                 // browser event has already occurred.
367                 if ( document.readyState === "complete" ) {
368                         return jQuery.ready();
369                 }
370
371                 // Mozilla, Opera and webkit nightlies currently support this event
372                 if ( document.addEventListener ) {
373                         // Use the handy event callback
374                         document.addEventListener( "DOMContentLoaded", function DOMContentLoaded() {
375                                 document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
376                                 jQuery.ready();
377                         }, false );
378                         
379                         // A fallback to window.onload, that will always work
380                         window.addEventListener( "load", jQuery.ready, false );
381
382                 // If IE event model is used
383                 } else if ( document.attachEvent ) {
384                         // ensure firing before onload,
385                         // maybe late but safe also for iframes
386                         document.attachEvent("onreadystatechange", function onreadystatechange() {
387                                 // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
388                                 if ( document.readyState === "complete" ) {
389                                         document.detachEvent( "onreadystatechange", onreadystatechange );
390                                         jQuery.ready();
391                                 }
392                         });
393                         
394                         // A fallback to window.onload, that will always work
395                         window.attachEvent( "onload", jQuery.ready );
396
397                         // If IE and not a frame
398                         // continually check to see if the document is ready
399                         var toplevel = false;
400
401                         try {
402                                 toplevel = window.frameElement == null;
403                         } catch(e){}
404
405                         if ( document.documentElement.doScroll && toplevel ) {
406                                 doScrollCheck();
407
408                                 function doScrollCheck() {
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( doScrollCheck, 1 );
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 frowned upon.
622         // More details: http://docs.jquery.com/Utilities/jQuery.browser
623         browser: {
624                 version: (/.*?(?:firefox|safari|opera|msie)[\/ ]([\d.]+)/.exec(userAgent) || [0,'0'])[1],
625                 safari: /safari/.test( userAgent ),
626                 opera: /opera/.test( userAgent ),
627                 msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
628                 firefox: /firefox/.test( userAgent )
629         }
630 });
631
632 // Deprecated
633 jQuery.browser.mozilla = /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent );
634
635 if ( indexOf ) {
636         jQuery.inArray = function( elem, array ) {
637                 return indexOf.call( array, elem );
638         };
639 }
640
641 // All jQuery objects should point back to these
642 rootjQuery = jQuery(document);
643
644 function evalScript( i, elem ) {
645         if ( elem.src ) {
646                 jQuery.ajax({
647                         url: elem.src,
648                         async: false,
649                         dataType: "script"
650                 });
651         } else {
652                 jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );
653         }
654
655         if ( elem.parentNode ) {
656                 elem.parentNode.removeChild( elem );
657         }
658 }
659
660 // Mutifunctional method to get and set values to a collection
661 // The value/s can be optionally by executed if its a function
662 function access( elems, key, value, exec, fn ) {
663         var l = elems.length;
664         
665         // Setting many attributes
666         if ( typeof key === "object" ) {
667                         for (var k in key) {
668                                 access(elems, k, key[k], exec, fn);
669                         }
670                 return elems;
671         }
672         
673         // Setting one attribute
674         if (value !== undefined) {
675                 // Optionally, function values get executed if exec is true
676                 exec = exec && jQuery.isFunction(value);
677                 
678                 for (var i = 0; i < l; i++) {
679                         var elem = elems[i],
680                                 val = exec ? value.call(elem, i) : value;
681                         fn(elem, key, val);
682                 }
683                 return elems;
684         }
685         
686         // Getting an attribute
687         return l ? fn(elems[0], key) : null;
688 }
689
690 function now() {
691         return (new Date).getTime();
692 }