Fix scope issue in DOM 2 event handlers
[jquery.git] / src / event / event.js
1 /*
2  * A number of helper functions used for managing events.
3  * Many of the ideas behind this code orignated from 
4  * Dean Edwards' addEvent library.
5  */
6 jQuery.event = {
7
8         // Bind an event to an element
9         // Original by Dean Edwards
10         add: function(element, type, handler, data) {
11                 // For whatever reason, IE has trouble passing the window object
12                 // around, causing it to be cloned in the process
13                 if ( jQuery.browser.msie && element.setInterval != undefined )
14                         element = window;
15                 
16                 // if data is passed, bind to handler 
17                 if( data != undefined ) { 
18                 // Create temporary function pointer to original handler 
19                         var fn = handler; 
20
21                         // Create unique handler function, wrapped around original handler 
22                         handler = function() { 
23                                 // Pass arguments and context to original handler 
24                                 return fn.apply(this, arguments); 
25                         };
26
27                         // Store data in unique handler 
28                         handler.data = data;
29
30                         // Set the guid of unique handler to the same of original handler, so it can be removed 
31                         handler.guid = fn.guid;
32                 }
33
34                 // Make sure that the function being executed has a unique ID
35                 if ( !handler.guid )
36                         handler.guid = this.guid++;
37
38                 // Init the element's event structure
39                 if (!element.$events)
40                         element.$events = {};
41
42                 // Get the current list of functions bound to this event
43                 var handlers = element.$events[type];
44
45                 // Init the event handler queue
46                 if (!handlers)
47                         handlers = element.$events[type] = {};
48
49                 // Add the function to the element's handler list
50                 handlers[handler.guid] = handler;
51                 
52                 if (!element.$handle) {
53                         element.$handle = function() {
54                                 jQuery.event.handle.apply(element, arguments);
55                         };
56
57                         // And bind the global event handler to the element
58                         if (element.addEventListener)
59                                 element.addEventListener(type, element.$handle, false);
60                         else if (element.attachEvent)
61                                 element.attachEvent("on" + type, element.$handle, false);
62                 }
63
64                 // Remember the function in a global list (for triggering)
65                 if (!this.global[type])
66                         this.global[type] = [];
67                 this.global[type].push( element );
68         },
69
70         guid: 1,
71         global: {},
72
73         // Detach an event or set of events from an element
74         remove: function(element, type, handler) {
75                 var events = element.$events, ret;
76
77                 if ( events ) {
78                         // type is actually an event object here
79                         if ( type && type.type ) {
80                                 handler = type.handler;
81                                 type = type.type;
82                         }
83                         
84                         if ( !type ) {
85                                 for ( type in events )
86                                         this.remove( element, type );
87
88                         } else if ( events[type] ) {
89                                 // remove the given handler for the given type
90                                 if ( handler )
91                                         delete events[type][handler.guid];
92                                 
93                                 // remove all handlers for the given type
94                                 else
95                                         for ( handler in element.$events[type] )
96                                                 delete events[type][handler];
97
98                                 // remove generic event handler if no more handlers exist
99                                 for ( ret in events[type] ) break;
100                                 if ( !ret ) {
101                                         if (element.removeEventListener)
102                                                 element.removeEventListener(type, element.$handle, false);
103                                         else if (element.detachEvent)
104                                                 element.detachEvent("on" + type, element.$handle, false);
105                                         ret = element.$handle = null;
106                                         delete events[type];
107                                 }
108                         }
109
110                         // Remove the expando if it's no longer used
111                         for ( ret in events ) break;
112                         if ( !ret )
113                                 element.$events = null;
114                 }
115         },
116
117         trigger: function(type, data, element) {
118                 // Clone the incoming data, if any
119                 data = jQuery.makeArray(data || []);
120
121                 // Handle a global trigger
122                 if ( !element )
123                         jQuery.each( this.global[type] || [], function(){
124                                 jQuery.event.trigger( type, data, this );
125                         });
126
127                 // Handle triggering a single element
128                 else {
129                         var val, ret, fn = jQuery.isFunction( element[ type ] );
130                         
131                         // Pass along a fake event
132                         data.unshift( this.fix({ type: type, target: element }) );
133
134                         // Trigger the event
135                         if ( (val = this.handle.apply( element, data )) !== false )
136                                 this.triggered = true;
137
138                         if ( fn && val !== false && !jQuery.nodeName(element, 'a') )
139                                 element[ type ]();
140
141                         this.triggered = false;
142                 }
143         },
144
145         handle: function(event) {
146                 // Handle the second event of a trigger and when
147                 // an event is called after a page has unloaded
148                 if ( typeof jQuery == "undefined" || jQuery.event.triggered ) return;
149
150                 // Empty object is for triggered events with no data
151                 event = jQuery.event.fix( event || window.event || {} ); 
152
153                 // returned undefined or false
154                 var returnValue;
155
156                 var c = this.$events[event.type];
157
158                 var args = [].slice.call( arguments, 1 );
159                 args.unshift( event );
160
161                 for ( var j in c ) {
162                         // Pass in a reference to the handler function itself
163                         // So that we can later remove it
164                         args[0].handler = c[j];
165                         args[0].data = c[j].data;
166
167                         if ( c[j].apply( this, args ) === false ) {
168                                 event.preventDefault();
169                                 event.stopPropagation();
170                                 returnValue = false;
171                         }
172                 }
173
174                 // Clean up added properties in IE to prevent memory leak
175                 if (jQuery.browser.msie) event.target = event.preventDefault = event.stopPropagation = event.handler = event.data = null;
176
177                 return returnValue;
178         },
179
180         fix: function(event) {
181                 // Fix target property, if necessary
182                 if ( !event.target && event.srcElement )
183                         event.target = event.srcElement;
184
185                 // Calculate pageX/Y if missing and clientX/Y available
186                 if ( event.pageX == undefined && event.clientX != undefined ) {
187                         var e = document.documentElement, b = document.body;
188                         event.pageX = event.clientX + (e.scrollLeft || b.scrollLeft);
189                         event.pageY = event.clientY + (e.scrollTop || b.scrollTop);
190                 }
191                                 
192                 // check if target is a textnode (safari)
193                 if (jQuery.browser.safari && event.target.nodeType == 3) {
194                         // store a copy of the original event object 
195                         // and clone because target is read only
196                         var originalEvent = event;
197                         event = jQuery.extend({}, originalEvent);
198                         
199                         // get parentnode from textnode
200                         event.target = originalEvent.target.parentNode;
201                         
202                         // add preventDefault and stopPropagation since 
203                         // they will not work on the clone
204                         event.preventDefault = function() {
205                                 return originalEvent.preventDefault();
206                         };
207                         event.stopPropagation = function() {
208                                 return originalEvent.stopPropagation();
209                         };
210                 }
211                 
212                 // fix preventDefault and stopPropagation
213                 if (!event.preventDefault)
214                         event.preventDefault = function() {
215                                 this.returnValue = false;
216                         };
217                         
218                 if (!event.stopPropagation)
219                         event.stopPropagation = function() {
220                                 this.cancelBubble = true;
221                         };
222                         
223                 return event;
224         }
225 };
226
227 jQuery.fn.extend({
228
229         /**
230          * Binds a handler to a particular event (like click) for each matched element.
231          * The event handler is passed an event object that you can use to prevent
232          * default behaviour. To stop both default action and event bubbling, your handler
233          * has to return false.
234          *
235          * In most cases, you can define your event handlers as anonymous functions
236          * (see first example). In cases where that is not possible, you can pass additional
237          * data as the second parameter (and the handler function as the third), see 
238          * second example.
239          *
240          * @example $("p").bind("click", function(){
241          *   alert( $(this).text() );
242          * });
243          * @before <p>Hello</p>
244          * @result alert("Hello")
245          *
246          * @example function handler(event) {
247          *   alert(event.data.foo);
248          * }
249          * $("p").bind("click", {foo: "bar"}, handler)
250          * @result alert("bar")
251          * @desc Pass some additional data to the event handler.
252          *
253          * @example $("form").bind("submit", function() { return false; })
254          * @desc Cancel a default action and prevent it from bubbling by returning false
255          * from your function.
256          *
257          * @example $("form").bind("submit", function(event){
258          *   event.preventDefault();
259          * });
260          * @desc Cancel only the default action by using the preventDefault method.
261          *
262          *
263          * @example $("form").bind("submit", function(event){
264          *   event.stopPropagation();
265          * });
266          * @desc Stop only an event from bubbling by using the stopPropagation method.
267          *
268          * @name bind
269          * @type jQuery
270          * @param String type An event type
271          * @param Object data (optional) Additional data passed to the event handler as event.data
272          * @param Function fn A function to bind to the event on each of the set of matched elements
273          * @cat Events
274          */
275         bind: function( type, data, fn ) {
276                 return this.each(function(){
277                         jQuery.event.add( this, type, fn || data, data );
278                 });
279         },
280         
281         /**
282          * Binds a handler to a particular event (like click) for each matched element.
283          * The handler is executed only once for each element. Otherwise, the same rules
284          * as described in bind() apply.
285          The event handler is passed an event object that you can use to prevent
286          * default behaviour. To stop both default action and event bubbling, your handler
287          * has to return false.
288          *
289          * In most cases, you can define your event handlers as anonymous functions
290          * (see first example). In cases where that is not possible, you can pass additional
291          * data as the second paramter (and the handler function as the third), see 
292          * second example.
293          *
294          * @example $("p").one("click", function(){
295          *   alert( $(this).text() );
296          * });
297          * @before <p>Hello</p>
298          * @result alert("Hello")
299          *
300          * @name one
301          * @type jQuery
302          * @param String type An event type
303          * @param Object data (optional) Additional data passed to the event handler as event.data
304          * @param Function fn A function to bind to the event on each of the set of matched elements
305          * @cat Events
306          */
307         one: function( type, data, fn ) {
308                 return this.each(function(){
309                         jQuery.event.add( this, type, function(event) {
310                                 jQuery(this).unbind(event);
311                                 return (fn || data).apply( this, arguments);
312                         }, data);
313                 });
314         },
315
316         /**
317          * The opposite of bind, removes a bound event from each of the matched
318          * elements.
319          *
320          * Without any arguments, all bound events are removed.
321          *
322          * If the type is provided, all bound events of that type are removed.
323          *
324          * If the function that was passed to bind is provided as the second argument,
325          * only that specific event handler is removed.
326          *
327          * @example $("p").unbind()
328          * @before <p onclick="alert('Hello');">Hello</p>
329          * @result [ <p>Hello</p> ]
330          *
331          * @example $("p").unbind( "click" )
332          * @before <p onclick="alert('Hello');">Hello</p>
333          * @result [ <p>Hello</p> ]
334          *
335          * @example $("p").unbind( "click", function() { alert("Hello"); } )
336          * @before <p onclick="alert('Hello');">Hello</p>
337          * @result [ <p>Hello</p> ]
338          *
339          * @name unbind
340          * @type jQuery
341          * @param String type (optional) An event type
342          * @param Function fn (optional) A function to unbind from the event on each of the set of matched elements
343          * @cat Events
344          */
345         unbind: function( type, fn ) {
346                 return this.each(function(){
347                         jQuery.event.remove( this, type, fn );
348                 });
349         },
350
351         /**
352          * Trigger a type of event on every matched element. This will also cause
353          * the default action of the browser with the same name (if one exists)
354          * to be executed. For example, passing 'submit' to the trigger()
355          * function will also cause the browser to submit the form. This
356          * default action can be prevented by returning false from one of
357          * the functions bound to the event.
358          *
359          * You can also trigger custom events registered with bind.
360          *
361          * @example $("p").trigger("click")
362          * @before <p click="alert('hello')">Hello</p>
363          * @result alert('hello')
364          *
365          * @example $("p").click(function(event, a, b) {
366          *   // when a normal click fires, a and b are undefined
367          *   // for a trigger like below a refers too "foo" and b refers to "bar"
368          * }).trigger("click", ["foo", "bar"]);
369          * @desc Example of how to pass arbitrary data to an event
370          * 
371          * @example $("p").bind("myEvent",function(event,message1,message2) {
372          *      alert(message1 + ' ' + message2);
373          * });
374          * $("p").trigger("myEvent",["Hello","World"]);
375          * @result alert('Hello World') // One for each paragraph
376          *
377          * @name trigger
378          * @type jQuery
379          * @param String type An event type to trigger.
380          * @param Array data (optional) Additional data to pass as arguments (after the event object) to the event handler
381          * @cat Events
382          */
383         trigger: function( type, data ) {
384                 return this.each(function(){
385                         jQuery.event.trigger( type, data, this );
386                 });
387         },
388
389         /**
390          * Toggle between two function calls every other click.
391          * Whenever a matched element is clicked, the first specified function 
392          * is fired, when clicked again, the second is fired. All subsequent 
393          * clicks continue to rotate through the two functions.
394          *
395          * Use unbind("click") to remove.
396          *
397          * @example $("p").toggle(function(){
398          *   $(this).addClass("selected");
399          * },function(){
400          *   $(this).removeClass("selected");
401          * });
402          * 
403          * @name toggle
404          * @type jQuery
405          * @param Function even The function to execute on every even click.
406          * @param Function odd The function to execute on every odd click.
407          * @cat Events
408          */
409         toggle: function() {
410                 // Save reference to arguments for access in closure
411                 var a = arguments;
412
413                 return this.click(function(e) {
414                         // Figure out which function to execute
415                         this.lastToggle = this.lastToggle == 0 ? 1 : 0;
416                         
417                         // Make sure that clicks stop
418                         e.preventDefault();
419                         
420                         // and execute the function
421                         return a[this.lastToggle].apply( this, [e] ) || false;
422                 });
423         },
424         
425         /**
426          * A method for simulating hovering (moving the mouse on, and off,
427          * an object). This is a custom method which provides an 'in' to a 
428          * frequent task.
429          *
430          * Whenever the mouse cursor is moved over a matched 
431          * element, the first specified function is fired. Whenever the mouse 
432          * moves off of the element, the second specified function fires. 
433          * Additionally, checks are in place to see if the mouse is still within 
434          * the specified element itself (for example, an image inside of a div), 
435          * and if it is, it will continue to 'hover', and not move out 
436          * (a common error in using a mouseout event handler).
437          *
438          * @example $("p").hover(function(){
439          *   $(this).addClass("hover");
440          * },function(){
441          *   $(this).removeClass("hover");
442          * });
443          *
444          * @name hover
445          * @type jQuery
446          * @param Function over The function to fire whenever the mouse is moved over a matched element.
447          * @param Function out The function to fire whenever the mouse is moved off of a matched element.
448          * @cat Events
449          */
450         hover: function(f,g) {
451                 
452                 // A private function for handling mouse 'hovering'
453                 function handleHover(e) {
454                         // Check if mouse(over|out) are still within the same parent element
455                         var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
456         
457                         // Traverse up the tree
458                         while ( p && p != this ) try { p = p.parentNode } catch(e) { p = this; };
459                         
460                         // If we actually just moused on to a sub-element, ignore it
461                         if ( p == this ) return false;
462                         
463                         // Execute the right function
464                         return (e.type == "mouseover" ? f : g).apply(this, [e]);
465                 }
466                 
467                 // Bind the function to the two event listeners
468                 return this.mouseover(handleHover).mouseout(handleHover);
469         },
470         
471         /**
472          * Bind a function to be executed whenever the DOM is ready to be
473          * traversed and manipulated. This is probably the most important 
474          * function included in the event module, as it can greatly improve
475          * the response times of your web applications.
476          *
477          * In a nutshell, this is a solid replacement for using window.onload, 
478          * and attaching a function to that. By using this method, your bound function 
479          * will be called the instant the DOM is ready to be read and manipulated, 
480          * which is when what 99.99% of all JavaScript code needs to run.
481          *
482          * There is one argument passed to the ready event handler: A reference to
483          * the jQuery function. You can name that argument whatever you like, and
484          * can therefore stick with the $ alias without risk of naming collisions.
485          * 
486          * Please ensure you have no code in your &lt;body&gt; onload event handler, 
487          * otherwise $(document).ready() may not fire.
488          *
489          * You can have as many $(document).ready events on your page as you like.
490          * The functions are then executed in the order they were added.
491          *
492          * @example $(document).ready(function(){ Your code here... });
493          *
494          * @example jQuery(function($) {
495          *   // Your code using failsafe $ alias here...
496          * });
497          * @desc Uses both the [[Core#.24.28_fn_.29|shortcut]] for $(document).ready() and the argument
498          * to write failsafe jQuery code using the $ alias, without relying on the
499          * global alias.
500          *
501          * @name ready
502          * @type jQuery
503          * @param Function fn The function to be executed when the DOM is ready.
504          * @cat Events
505          * @see $.noConflict()
506          * @see $(Function)
507          */
508         ready: function(f) {
509                 // If the DOM is already ready
510                 if ( jQuery.isReady )
511                         // Execute the function immediately
512                         f.apply( document, [jQuery] );
513                         
514                 // Otherwise, remember the function for later
515                 else {
516                         // Add the function to the wait list
517                         jQuery.readyList.push( function() { return f.apply(this, [jQuery]) } );
518                 }
519         
520                 return this;
521         }
522 });
523
524 jQuery.extend({
525         /*
526          * All the code that makes DOM Ready work nicely.
527          */
528         isReady: false,
529         readyList: [],
530         
531         // Handle when the DOM is ready
532         ready: function() {
533                 // Make sure that the DOM is not already loaded
534                 if ( !jQuery.isReady ) {
535                         // Remember that the DOM is ready
536                         jQuery.isReady = true;
537                         
538                         // If there are functions bound, to execute
539                         if ( jQuery.readyList ) {
540                                 // Execute all of them
541                                 jQuery.each( jQuery.readyList, function(){
542                                         this.apply( document );
543                                 });
544                                 
545                                 // Reset the list of functions
546                                 jQuery.readyList = null;
547                         }
548                         // Remove event lisenter to avoid memory leak
549                         if ( jQuery.browser.mozilla || jQuery.browser.opera )
550                                 document.removeEventListener( "DOMContentLoaded", jQuery.ready, false );
551                 }
552         }
553 });
554
555 new function(){
556
557         /**
558          * Bind a function to the scroll event of each matched element.
559          *
560          * @example $("p").scroll( function() { alert("Hello"); } );
561          * @before <p>Hello</p>
562          * @result <p onscroll="alert('Hello');">Hello</p>
563          *
564          * @name scroll
565          * @type jQuery
566          * @param Function fn A function to bind to the scroll event on each of the matched elements.
567          * @cat Events
568          */
569
570         /**
571          * Bind a function to the submit event of each matched element.
572          *
573          * @example $("#myform").submit( function() {
574          *   return $("input", this).val().length > 0;
575          * } );
576          * @before <form id="myform"><input /></form>
577          * @desc Prevents the form submission when the input has no value entered.
578          *
579          * @name submit
580          * @type jQuery
581          * @param Function fn A function to bind to the submit event on each of the matched elements.
582          * @cat Events
583          */
584
585         /**
586          * Trigger the submit event of each matched element. This causes all of the functions
587          * that have been bound to that submit event to be executed, and calls the browser's
588          * default submit action on the matching element(s). This default action can be prevented
589          * by returning false from one of the functions bound to the submit event.
590          *
591          * Note: This does not execute the submit method of the form element! If you need to
592          * submit the form via code, you have to use the DOM method, eg. $("form")[0].submit();
593          *
594          * @example $("form").submit();
595          * @desc Triggers all submit events registered to the matched form(s), and submits them.
596          *
597          * @name submit
598          * @type jQuery
599          * @cat Events
600          */
601
602         /**
603          * Bind a function to the focus event of each matched element.
604          *
605          * @example $("p").focus( function() { alert("Hello"); } );
606          * @before <p>Hello</p>
607          * @result <p onfocus="alert('Hello');">Hello</p>
608          *
609          * @name focus
610          * @type jQuery
611          * @param Function fn A function to bind to the focus event on each of the matched elements.
612          * @cat Events
613          */
614
615         /**
616          * Trigger the focus event of each matched element. This causes all of the functions
617          * that have been bound to thet focus event to be executed.
618          *
619          * Note: This does not execute the focus method of the underlying elements! If you need to
620          * focus an element via code, you have to use the DOM method, eg. $("#myinput")[0].focus();
621          *
622          * @example $("p").focus();
623          * @before <p onfocus="alert('Hello');">Hello</p>
624          * @result alert('Hello');
625          *
626          * @name focus
627          * @type jQuery
628          * @cat Events
629          */
630
631         /**
632          * Bind a function to the keydown event of each matched element.
633          *
634          * @example $("p").keydown( function() { alert("Hello"); } );
635          * @before <p>Hello</p>
636          * @result <p onkeydown="alert('Hello');">Hello</p>
637          *
638          * @name keydown
639          * @type jQuery
640          * @param Function fn A function to bind to the keydown event on each of the matched elements.
641          * @cat Events
642          */
643
644         /**
645          * Bind a function to the dblclick event of each matched element.
646          *
647          * @example $("p").dblclick( function() { alert("Hello"); } );
648          * @before <p>Hello</p>
649          * @result <p ondblclick="alert('Hello');">Hello</p>
650          *
651          * @name dblclick
652          * @type jQuery
653          * @param Function fn A function to bind to the dblclick event on each of the matched elements.
654          * @cat Events
655          */
656
657         /**
658          * Bind a function to the keypress event of each matched element.
659          *
660          * @example $("p").keypress( function() { alert("Hello"); } );
661          * @before <p>Hello</p>
662          * @result <p onkeypress="alert('Hello');">Hello</p>
663          *
664          * @name keypress
665          * @type jQuery
666          * @param Function fn A function to bind to the keypress event on each of the matched elements.
667          * @cat Events
668          */
669
670         /**
671          * Bind a function to the error event of each matched element.
672          *
673          * @example $("p").error( function() { alert("Hello"); } );
674          * @before <p>Hello</p>
675          * @result <p onerror="alert('Hello');">Hello</p>
676          *
677          * @name error
678          * @type jQuery
679          * @param Function fn A function to bind to the error event on each of the matched elements.
680          * @cat Events
681          */
682
683         /**
684          * Bind a function to the blur event of each matched element.
685          *
686          * @example $("p").blur( function() { alert("Hello"); } );
687          * @before <p>Hello</p>
688          * @result <p onblur="alert('Hello');">Hello</p>
689          *
690          * @name blur
691          * @type jQuery
692          * @param Function fn A function to bind to the blur event on each of the matched elements.
693          * @cat Events
694          */
695
696         /**
697          * Trigger the blur event of each matched element. This causes all of the functions
698          * that have been bound to that blur event to be executed, and calls the browser's
699          * default blur action on the matching element(s). This default action can be prevented
700          * by returning false from one of the functions bound to the blur event.
701          *
702          * Note: This does not execute the blur method of the underlying elements! If you need to
703          * blur an element via code, you have to use the DOM method, eg. $("#myinput")[0].blur();
704          *
705          * @example $("p").blur();
706          * @before <p onblur="alert('Hello');">Hello</p>
707          * @result alert('Hello');
708          *
709          * @name blur
710          * @type jQuery
711          * @cat Events
712          */
713
714         /**
715          * Bind a function to the load event of each matched element.
716          *
717          * @example $("p").load( function() { alert("Hello"); } );
718          * @before <p>Hello</p>
719          * @result <p onload="alert('Hello');">Hello</p>
720          *
721          * @name load
722          * @type jQuery
723          * @param Function fn A function to bind to the load event on each of the matched elements.
724          * @cat Events
725          */
726
727         /**
728          * Bind a function to the select event of each matched element.
729          *
730          * @example $("p").select( function() { alert("Hello"); } );
731          * @before <p>Hello</p>
732          * @result <p onselect="alert('Hello');">Hello</p>
733          *
734          * @name select
735          * @type jQuery
736          * @param Function fn A function to bind to the select event on each of the matched elements.
737          * @cat Events
738          */
739
740         /**
741          * Trigger the select event of each matched element. This causes all of the functions
742          * that have been bound to that select event to be executed, and calls the browser's
743          * default select action on the matching element(s). This default action can be prevented
744          * by returning false from one of the functions bound to the select event.
745          *
746          * @example $("p").select();
747          * @before <p onselect="alert('Hello');">Hello</p>
748          * @result alert('Hello');
749          *
750          * @name select
751          * @type jQuery
752          * @cat Events
753          */
754
755         /**
756          * Bind a function to the mouseup event of each matched element.
757          *
758          * @example $("p").mouseup( function() { alert("Hello"); } );
759          * @before <p>Hello</p>
760          * @result <p onmouseup="alert('Hello');">Hello</p>
761          *
762          * @name mouseup
763          * @type jQuery
764          * @param Function fn A function to bind to the mouseup event on each of the matched elements.
765          * @cat Events
766          */
767
768         /**
769          * Bind a function to the unload event of each matched element.
770          *
771          * @example $("p").unload( function() { alert("Hello"); } );
772          * @before <p>Hello</p>
773          * @result <p onunload="alert('Hello');">Hello</p>
774          *
775          * @name unload
776          * @type jQuery
777          * @param Function fn A function to bind to the unload event on each of the matched elements.
778          * @cat Events
779          */
780
781         /**
782          * Bind a function to the change event of each matched element.
783          *
784          * @example $("p").change( function() { alert("Hello"); } );
785          * @before <p>Hello</p>
786          * @result <p onchange="alert('Hello');">Hello</p>
787          *
788          * @name change
789          * @type jQuery
790          * @param Function fn A function to bind to the change event on each of the matched elements.
791          * @cat Events
792          */
793
794         /**
795          * Bind a function to the mouseout event of each matched element.
796          *
797          * @example $("p").mouseout( function() { alert("Hello"); } );
798          * @before <p>Hello</p>
799          * @result <p onmouseout="alert('Hello');">Hello</p>
800          *
801          * @name mouseout
802          * @type jQuery
803          * @param Function fn A function to bind to the mouseout event on each of the matched elements.
804          * @cat Events
805          */
806
807         /**
808          * Bind a function to the keyup event of each matched element.
809          *
810          * @example $("p").keyup( function() { alert("Hello"); } );
811          * @before <p>Hello</p>
812          * @result <p onkeyup="alert('Hello');">Hello</p>
813          *
814          * @name keyup
815          * @type jQuery
816          * @param Function fn A function to bind to the keyup event on each of the matched elements.
817          * @cat Events
818          */
819
820         /**
821          * Bind a function to the click event of each matched element.
822          *
823          * @example $("p").click( function() { alert("Hello"); } );
824          * @before <p>Hello</p>
825          * @result <p onclick="alert('Hello');">Hello</p>
826          *
827          * @name click
828          * @type jQuery
829          * @param Function fn A function to bind to the click event on each of the matched elements.
830          * @cat Events
831          */
832
833         /**
834          * Trigger the click event of each matched element. This causes all of the functions
835          * that have been bound to thet click event to be executed.
836          *
837          * @example $("p").click();
838          * @before <p onclick="alert('Hello');">Hello</p>
839          * @result alert('Hello');
840          *
841          * @name click
842          * @type jQuery
843          * @cat Events
844          */
845
846         /**
847          * Bind a function to the resize event of each matched element.
848          *
849          * @example $("p").resize( function() { alert("Hello"); } );
850          * @before <p>Hello</p>
851          * @result <p onresize="alert('Hello');">Hello</p>
852          *
853          * @name resize
854          * @type jQuery
855          * @param Function fn A function to bind to the resize event on each of the matched elements.
856          * @cat Events
857          */
858
859         /**
860          * Bind a function to the mousemove event of each matched element.
861          *
862          * @example $("p").mousemove( function() { alert("Hello"); } );
863          * @before <p>Hello</p>
864          * @result <p onmousemove="alert('Hello');">Hello</p>
865          *
866          * @name mousemove
867          * @type jQuery
868          * @param Function fn A function to bind to the mousemove event on each of the matched elements.
869          * @cat Events
870          */
871
872         /**
873          * Bind a function to the mousedown event of each matched element.
874          *
875          * @example $("p").mousedown( function() { alert("Hello"); } );
876          * @before <p>Hello</p>
877          * @result <p onmousedown="alert('Hello');">Hello</p>
878          *
879          * @name mousedown
880          * @type jQuery
881          * @param Function fn A function to bind to the mousedown event on each of the matched elements.
882          * @cat Events
883          */
884          
885         /**
886          * Bind a function to the mouseover event of each matched element.
887          *
888          * @example $("p").mouseover( function() { alert("Hello"); } );
889          * @before <p>Hello</p>
890          * @result <p onmouseover="alert('Hello');">Hello</p>
891          *
892          * @name mouseover
893          * @type jQuery
894          * @param Function fn A function to bind to the mousedown event on each of the matched elements.
895          * @cat Events
896          */
897         jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
898                 "mousedown,mouseup,mousemove,mouseover,mouseout,change,select," + 
899                 "submit,keydown,keypress,keyup,error").split(","), function(i,o){
900                 
901                 // Handle event binding
902                 jQuery.fn[o] = function(f){
903                         return f ? this.bind(o, f) : this.trigger(o);
904                 };
905                         
906         });
907         
908         // If Mozilla is used
909         if ( jQuery.browser.mozilla || jQuery.browser.opera )
910                 // Use the handy event callback
911                 document.addEventListener( "DOMContentLoaded", jQuery.ready, false );
912         
913         // If IE is used, use the excellent hack by Matthias Miller
914         // http://www.outofhanwell.com/blog/index.php?title=the_window_onload_problem_revisited
915         else if ( jQuery.browser.msie ) {
916         
917                 // Only works if you document.write() it
918                 document.write("<scr" + "ipt id=__ie_init defer=true " + 
919                         "src=//:><\/script>");
920         
921                 // Use the defer script hack
922                 var script = document.getElementById("__ie_init");
923                 
924                 // script does not exist if jQuery is loaded dynamically
925                 if ( script ) 
926                         script.onreadystatechange = function() {
927                                 if ( this.readyState != "complete" ) return;
928                                 this.parentNode.removeChild( this );
929                                 jQuery.ready();
930                         };
931         
932                 // Clear from memory
933                 script = null;
934         
935         // If Safari  is used
936         } else if ( jQuery.browser.safari )
937                 // Continually check to see if the document.readyState is valid
938                 jQuery.safariTimer = setInterval(function(){
939                         // loaded and complete are both valid states
940                         if ( document.readyState == "loaded" || 
941                                 document.readyState == "complete" ) {
942         
943                                 // If either one are found, remove the timer
944                                 clearInterval( jQuery.safariTimer );
945                                 jQuery.safariTimer = null;
946         
947                                 // and execute any waiting functions
948                                 jQuery.ready();
949                         }
950                 }, 10); 
951
952         // A fallback to window.onload, that will always work
953         jQuery.event.add( window, "load", jQuery.ready );
954         
955 };
956
957 // Clean up after IE to avoid memory leaks
958 if (jQuery.browser.msie)
959         jQuery(window).one("unload", function() {
960                 var global = jQuery.event.global;
961                 for ( var type in global ) {
962                         var els = global[type], i = els.length;
963                         if ( i && type != 'unload' )
964                                 do
965                                         jQuery.event.remove(els[i-1], type);
966                                 while (--i);
967                 }
968         });