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