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