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