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