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