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