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