b51886f4857eea3a05b7effeb17079c8b7fe8c7f
[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 arguments.length === 0 ?
5                         rootjQuery :
6                         new jQuery.fn.init( selector, context );
7         },
8
9         // Map over jQuery in case of overwrite
10         _jQuery = window.jQuery,
11
12         // Map over the $ in case of overwrite
13         _$ = window.$,
14
15         // Use the correct document accordingly with window argument (sandbox)
16         document = window.document,
17
18         // A central reference to the root jQuery(document)
19         rootjQuery,
20
21         // A simple way to check for HTML strings or ID strings
22         // (both of which we optimize for)
23         quickExpr = /^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,
24
25         // Is it a simple selector
26         isSimple = /^.[^:#\[\.,]*$/,
27
28         // Keep a UserAgent string for use with jQuery.browser
29         userAgent = navigator.userAgent.toLowerCase(),
30
31         // Save a reference to the core toString method
32         toString = Object.prototype.toString;
33
34 // Expose jQuery to the global object
35 window.jQuery = window.$ = jQuery;
36
37 jQuery.fn = jQuery.prototype = {
38         init: function( selector, context ) {
39                 var match, elem, ret;
40
41                 // Handle $(""), $(null), or $(undefined)
42                 if ( !selector ) {
43                         this.length = 0;
44                         return this;
45                 }
46
47                 // Handle $(DOMElement)
48                 if ( selector.nodeType ) {
49                         this[0] = selector;
50                         this.length = 1;
51                         this.context = selector;
52                         return this;
53                 }
54
55                 // Handle HTML strings
56                 if ( typeof selector === "string" ) {
57                         // Are we dealing with HTML string or an ID?
58                         match = quickExpr.exec( selector );
59
60                         // Verify a match, and that no context was specified for #id
61                         if ( match && (match[1] || !context) ) {
62
63                                 // HANDLE: $(html) -> $(array)
64                                 if ( match[1] ) {
65                                         selector = jQuery.clean( [ match[1] ], context );
66
67                                 // HANDLE: $("#id")
68                                 } else {
69                                         elem = document.getElementById( match[3] );
70
71                                         // Handle the case where IE and Opera return items
72                                         // by name instead of ID
73                                         if ( elem && elem.id !== match[3] ) {
74                                                 return rootjQuery.find( selector );
75                                         }
76
77                                         // Otherwise, we inject the element directly into the jQuery object
78                                         this.length = elem ? 1 : 0;
79                                         if ( elem ) {
80                                                 this[0] = elem;
81                                         }
82                                         this.context = document;
83                                         this.selector = selector;
84                                         return this;
85                                 }
86
87                         // HANDLE: $(expr, $(...))
88                         } else if ( !context || context.jquery ) {
89                                 return (context || rootjQuery).find( selector );
90
91                         // HANDLE: $(expr, context)
92                         // (which is just equivalent to: $(context).find(expr)
93                         } else {
94                                 return jQuery( context ).find( selector );
95                         }
96
97                 // HANDLE: $(function)
98                 // Shortcut for document ready
99                 } else if ( jQuery.isFunction( selector ) ) {
100                         return rootjQuery.ready( selector );
101                 }
102
103                 // Make sure that old selector state is passed along
104                 if ( selector.selector && selector.context ) {
105                         this.selector = selector.selector;
106                         this.context = selector.context;
107                 }
108
109                 return this.setArray(jQuery.isArray( selector ) ?
110                         selector :
111                         jQuery.makeArray(selector));
112         },
113
114         // Start with an empty selector
115         selector: "",
116
117         // The current version of jQuery being used
118         jquery: "@VERSION",
119
120         // The number of elements contained in the matched element set
121         size: function() {
122                 return this.length;
123         },
124
125         toArray: Array.prototype.slice,
126
127         // Get the Nth element in the matched element set OR
128         // Get the whole matched element set as a clean array
129         get: function( num ) {
130                 return num == null ?
131
132                         // Return a 'clean' array
133                         this.toArray() :
134
135                         // Return just the object
136                         ( num < 0 ? this.toArray.call(this, num)[0] : this[ num ] );
137         },
138
139         // Take an array of elements and push it onto the stack
140         // (returning the new matched element set)
141         pushStack: function( elems, name, selector ) {
142                 // Build a new jQuery matched element set
143                 var ret = jQuery( elems || null );
144
145                 // Add the old object onto the stack (as a reference)
146                 ret.prevObject = this;
147
148                 ret.context = this.context;
149
150                 if ( name === "find" ) {
151                         ret.selector = this.selector + (this.selector ? " " : "") + selector;
152                 } else if ( name ) {
153                         ret.selector = this.selector + "." + name + "(" + selector + ")";
154                 }
155
156                 // Return the newly-formed element set
157                 return ret;
158         },
159
160         // Force the current matched set of elements to become
161         // the specified array of elements (destroying the stack in the process)
162         // You should use pushStack() in order to do this, but maintain the stack
163         setArray: function( elems ) {
164                 // Resetting the length to 0, then using the native Array push
165                 // is a super-fast way to populate an object with array-like properties
166                 this.length = 0;
167                 Array.prototype.push.apply( this, elems );
168
169                 return this;
170         },
171
172         // Execute a callback for every element in the matched set.
173         // (You can seed the arguments with an array of args, but this is
174         // only used internally.)
175         each: function( callback, args ) {
176                 return jQuery.each( this, callback, args );
177         },
178
179         // Determine the position of an element within
180         // the matched set of elements
181         index: function( elem ) {
182                 if ( !elem || typeof elem === "string" ) {
183                         return jQuery.inArray( this[0],
184                                 // If it receives a string, the selector is used
185                                 // If it receives nothing, the siblings are used
186                                 elem ? jQuery( elem ) : this.parent().children() );
187                 }
188                 // Locate the position of the desired element
189                 return jQuery.inArray(
190                         // If it receives a jQuery object, the first element is used
191                         elem.jquery ? elem[0] : elem, this );
192         },
193
194         is: function( selector ) {
195                 return !!selector && jQuery.multiFilter( selector, this ).length > 0;
196         },
197
198         // For internal use only.
199         // Behaves like an Array's method, not like a jQuery method.
200         push: [].push,
201         sort: [].sort,
202         splice: [].splice
203 };
204
205 // Give the init function the jQuery prototype for later instantiation
206 jQuery.fn.init.prototype = jQuery.fn;
207
208 jQuery.extend = jQuery.fn.extend = function() {
209         // copy reference to target object
210         var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options, name, src, copy;
211
212         // Handle a deep copy situation
213         if ( typeof target === "boolean" ) {
214                 deep = target;
215                 target = arguments[1] || {};
216                 // skip the boolean and the target
217                 i = 2;
218         }
219
220         // Handle case when target is a string or something (possible in deep copy)
221         if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
222                 target = {};
223         }
224
225         // extend jQuery itself if only one argument is passed
226         if ( length === i ) {
227                 target = this;
228                 --i;
229         }
230
231         for ( ; i < length; i++ ) {
232                 // Only deal with non-null/undefined values
233                 if ( (options = arguments[ i ]) != null ) {
234                         // Extend the base object
235                         for ( name in options ) {
236                                 src = target[ name ];
237                                 copy = options[ name ];
238
239                                 // Prevent never-ending loop
240                                 if ( target === copy ) {
241                                         continue;
242                                 }
243
244                                 // Recurse if we're merging object values
245                                 if ( deep && copy && typeof copy === "object" && !copy.nodeType ) {
246                                         var clone;
247
248                                         if( src ) clone = src;
249                                         else if( jQuery.isArray(copy) ) clone = [ ];
250                                         else if( jQuery.isObject(copy) ) clone = { };
251                                         else clone = copy;
252
253                                         // Never move original objects, clone them
254                                         target[ name ] = jQuery.extend( deep, clone, copy );
255
256                                 // Don't bring in undefined values
257                                 } else if ( copy !== undefined ) {
258                                         target[ name ] = copy;
259                                 }
260                         }
261                 }
262         }
263
264         // Return the modified object
265         return target;
266 };
267
268 jQuery.extend({
269         noConflict: function( deep ) {
270                 window.$ = _$;
271
272                 if ( deep ) {
273                         window.jQuery = _jQuery;
274                 }
275
276                 return jQuery;
277         },
278
279         // See test/unit/core.js for details concerning isFunction.
280         // Since version 1.3, DOM methods and functions like alert
281         // aren't supported. They return false on IE (#2968).
282         isFunction: function( obj ) {
283                 return toString.call(obj) === "[object Function]";
284         },
285
286         isArray: function( obj ) {
287                 return toString.call(obj) === "[object Array]";
288         },
289
290         isObject: function( obj ) {
291                 return this.constructor.call(obj) === Object;
292         },
293
294         // check if an element is in a (or is an) XML document
295         isXMLDoc: function( elem ) {
296                 return elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML" ||
297                         !!elem.ownerDocument && elem.ownerDocument.documentElement.nodeName !== "HTML";
298         },
299
300         // Evalulates a script in a global context
301         globalEval: function( data ) {
302                 if ( data && /\S/.test(data) ) {
303                         // Inspired by code by Andrea Giammarchi
304                         // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
305                         var head = document.getElementsByTagName("head")[0] || document.documentElement,
306                                 script = document.createElement("script");
307
308                         script.type = "text/javascript";
309                         if ( jQuery.support.scriptEval ) {
310                                 script.appendChild( document.createTextNode( data ) );
311                         } else {
312                                 script.text = data;
313                         }
314
315                         // Use insertBefore instead of appendChild  to circumvent an IE6 bug.
316                         // This arises when a base node is used (#2709).
317                         head.insertBefore( script, head.firstChild );
318                         head.removeChild( script );
319                 }
320         },
321
322         nodeName: function( elem, name ) {
323                 return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
324         },
325
326         // args is for internal usage only
327         each: function( object, callback, args ) {
328                 var name, i = 0,
329                         length = object.length,
330                         isObj = length === undefined || jQuery.isFunction(object);
331
332                 if ( args ) {
333                         if ( isObj ) {
334                                 for ( name in object ) {
335                                         if ( callback.apply( object[ name ], args ) === false ) {
336                                                 break;
337                                         }
338                                 }
339                         } else {
340                                 for ( ; i < length; ) {
341                                         if ( callback.apply( object[ i++ ], args ) === false ) {
342                                                 break;
343                                         }
344                                 }
345                         }
346
347                 // A special, fast, case for the most common use of each
348                 } else {
349                         if ( isObj ) {
350                                 for ( name in object ) {
351                                         if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
352                                                 break;
353                                         }
354                                 }
355                         } else {
356                                 for ( var value = object[0];
357                                         i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {}
358                         }
359                 }
360
361                 return object;
362         },
363
364         trim: function( text ) {
365                 return (text || "").replace( /^\s+|\s+$/g, "" );
366         },
367
368         makeArray: function( array ) {
369                 var ret = [], i;
370
371                 if ( array != null ) {
372                         i = array.length;
373
374                         // The window, strings (and functions) also have 'length'
375                         if ( i == null || typeof array === "string" || jQuery.isFunction(array) || array.setInterval ) {
376                                 ret[0] = array;
377                         } else {
378                                 while ( i ) {
379                                         ret[--i] = array[i];
380                                 }
381                         }
382                 }
383
384                 return ret;
385         },
386
387         inArray: function( elem, array ) {
388                 for ( var i = 0, length = array.length; i < length; i++ ) {
389                         if ( array[ i ] === elem ) {
390                                 return i;
391                         }
392                 }
393
394                 return -1;
395         },
396
397         merge: function( first, second ) {
398                 // We have to loop this way because IE & Opera overwrite the length
399                 // expando of getElementsByTagName
400                 var i = 0, elem, pos = first.length;
401
402                 // Also, we need to make sure that the correct elements are being returned
403                 // (IE returns comment nodes in a '*' query)
404                 if ( !jQuery.support.getAll ) {
405                         while ( (elem = second[ i++ ]) != null ) {
406                                 if ( elem.nodeType !== 8 ) {
407                                         first[ pos++ ] = elem;
408                                 }
409                         }
410
411                 } else {
412                         while ( (elem = second[ i++ ]) != null ) {
413                                 first[ pos++ ] = elem;
414                         }
415                 }
416
417                 return first;
418         },
419
420         unique: function( array ) {
421                 var ret = [], done = {}, id;
422
423                 try {
424                         for ( var i = 0, length = array.length; i < length; i++ ) {
425                                 id = jQuery.data( array[ i ] );
426
427                                 if ( !done[ id ] ) {
428                                         done[ id ] = true;
429                                         ret.push( array[ i ] );
430                                 }
431                         }
432                 } catch( e ) {
433                         ret = array;
434                 }
435
436                 return ret;
437         },
438
439         grep: function( elems, callback, inv ) {
440                 var ret = [];
441
442                 // Go through the array, only saving the items
443                 // that pass the validator function
444                 for ( var i = 0, length = elems.length; i < length; i++ ) {
445                         if ( !inv !== !callback( elems[ i ], i ) ) {
446                                 ret.push( elems[ i ] );
447                         }
448                 }
449
450                 return ret;
451         },
452
453         map: function( elems, callback ) {
454                 var ret = [], value;
455
456                 // Go through the array, translating each of the items to their
457                 // new value (or values).
458                 for ( var i = 0, length = elems.length; i < length; i++ ) {
459                         value = callback( elems[ i ], i );
460
461                         if ( value != null ) {
462                                 ret[ ret.length ] = value;
463                         }
464                 }
465
466                 return ret.concat.apply( [], ret );
467         },
468
469         // Use of jQuery.browser is deprecated.
470         // It's included for backwards compatibility and plugins,
471         // although they should work to migrate away.
472         browser: {
473                 version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1],
474                 safari: /webkit/.test( userAgent ),
475                 opera: /opera/.test( userAgent ),
476                 msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
477                 mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
478         }
479 });
480
481 // All jQuery objects should point back to these
482 rootjQuery = jQuery(document);
483
484 function evalScript( i, elem ) {
485         if ( elem.src ) {
486                 jQuery.ajax({
487                         url: elem.src,
488                         async: false,
489                         dataType: "script"
490                 });
491         } else {
492                 jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );
493         }
494
495         if ( elem.parentNode ) {
496                 elem.parentNode.removeChild( elem );
497         }
498 }
499
500 function now() {
501         return (new Date).getTime();
502 }