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