Short-circuit jQuery.event.fix if it has already fixed the current event object.
[jquery.git] / src / 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(elem, types, handler, data) {
11                 if ( elem.nodeType == 3 || elem.nodeType == 8 )
12                         return;
13
14                 // For whatever reason, IE has trouble passing the window object
15                 // around, causing it to be cloned in the process
16                 if ( jQuery.browser.msie && elem.setInterval != undefined )
17                         elem = window;
18
19                 // Make sure that the function being executed has a unique ID
20                 if ( !handler.guid )
21                         handler.guid = this.guid++;
22                         
23                 // if data is passed, bind to handler 
24                 if( data != undefined ) { 
25                         // Create temporary function pointer to original handler 
26                         var fn = handler; 
27
28                         // Create unique handler function, wrapped around original handler 
29                         handler = function() { 
30                                 // Pass arguments and context to original handler 
31                                 return fn.apply(this, arguments); 
32                         };
33
34                         // Store data in unique handler 
35                         handler.data = data;
36
37                         // Set the guid of unique handler to the same of original handler, so it can be removed 
38                         handler.guid = fn.guid;
39                 }
40
41                 // Init the element's event structure
42                 var events = jQuery.data(elem, "events") || jQuery.data(elem, "events", {}),
43                         handle = jQuery.data(elem, "handle") || jQuery.data(elem, "handle", function(){
44                                 // returned undefined or false
45                                 var val;
46
47                                 // Handle the second event of a trigger and when
48                                 // an event is called after a page has unloaded
49                                 if ( typeof jQuery == "undefined" || jQuery.event.triggered )
50                                         return val;
51                 
52                                 val = jQuery.event.handle.apply(elem, arguments);
53                 
54                                 return val;
55                         });
56                         
57                         // Handle multiple events seperated by a space
58                         // jQuery(...).bind("mouseover mouseout", fn);
59                         jQuery.each(types.split(/\s+/), function(index, type) {
60                                 // Namespaced event handlers
61                                 var parts = type.split(".");
62                                 type = parts[0];
63                                 handler.type = parts[1];
64
65                                 // Get the current list of functions bound to this event
66                                 var handlers = events[type];
67
68                                 // Init the event handler queue
69                                 if (!handlers) {
70                                         handlers = events[type] = {};
71                 
72                                         // Check for a special event handler
73                                         // Only use addEventListener/attachEvent if the special
74                                         // events handler returns false
75                                         if ( !jQuery.event.special[type] || jQuery.event.special[type].setup.call(elem) === false ) {
76                                                 // Bind the global event handler to the element
77                                                 if (elem.addEventListener)
78                                                         elem.addEventListener(type, handle, false);
79                                                 else if (elem.attachEvent)
80                                                         elem.attachEvent("on" + type, handle);
81                                         }
82                                 }
83
84                                 // Add the function to the element's handler list
85                                 handlers[handler.guid] = handler;
86
87                                 // Keep track of which events have been used, for global triggering
88                                 jQuery.event.global[type] = true;
89                         });
90         },
91
92         guid: 1,
93         global: {},
94
95         // Detach an event or set of events from an element
96         remove: function(elem, types, handler) {
97                 // don't do events on text and comment nodes
98                 if ( elem.nodeType == 3 || elem.nodeType == 8 )
99                         return;
100
101                 var events = jQuery.data(elem, "events"), ret, index;
102
103                 if ( events ) {
104                         // Unbind all events for the element
105                         if ( types == undefined )
106                                 for ( var type in events )
107                                         this.remove( elem, type );
108                         else {
109                                 // types is actually an event object here
110                                 if ( types.type ) {
111                                         handler = types.handler;
112                                         types = types.type;
113                                 }
114                                 
115                                 // Handle multiple events seperated by a space
116                                 // jQuery(...).unbind("mouseover mouseout", fn);
117                                 jQuery.each(types.split(/\s+/), function(index, type){
118                                         // Namespaced event handlers
119                                         var parts = type.split(".");
120                                         type = parts[0];
121                                         
122                                         if ( events[type] ) {
123                                                 // remove the given handler for the given type
124                                                 if ( handler )
125                                                         delete events[type][handler.guid];
126                         
127                                                 // remove all handlers for the given type
128                                                 else
129                                                         for ( handler in events[type] )
130                                                                 // Handle the removal of namespaced events
131                                                                 if ( !parts[1] || events[type][handler].type == parts[1] )
132                                                                         delete events[type][handler];
133
134                                                 // remove generic event handler if no more handlers exist
135                                                 for ( ret in events[type] ) break;
136                                                 if ( !ret ) {
137                                                         if ( !jQuery.event.special[type] || jQuery.event.special[type].teardown.call(elem) === false ) {
138                                                                 if (elem.removeEventListener)
139                                                                         elem.removeEventListener(type, jQuery.data(elem, "handle"), false);
140                                                                 else if (elem.detachEvent)
141                                                                         elem.detachEvent("on" + type, jQuery.data(elem, "handle"));
142                                                         }
143                                                         ret = null;
144                                                         delete events[type];
145                                                 }
146                                         }
147                                 });
148                         }
149
150                         // Remove the expando if it's no longer used
151                         for ( ret in events ) break;
152                         if ( !ret ) {
153                                 jQuery.removeData( elem, "events" );
154                                 jQuery.removeData( elem, "handle" );
155                         }
156                 }
157         },
158
159         trigger: function(type, data, elem, donative, extra) {
160                 // Clone the incoming data, if any
161                 data = jQuery.makeArray(data || []);
162
163                 // Handle a global trigger
164                 if ( !elem ) {
165                         // Only trigger if we've ever bound an event for it
166                         if ( this.global[type] )
167                                 jQuery("*").add([window, document]).trigger(type, data);
168
169                 // Handle triggering a single element
170                 } else {
171                         // don't do events on text and comment nodes
172                         if ( elem.nodeType == 3 || elem.nodeType == 8 )
173                                 return undefined;
174
175                         var val, ret, fn = jQuery.isFunction( elem[ type ] || null ),
176                                 // Check to see if we need to provide a fake event, or not
177                                 event = !data[0] || !data[0].preventDefault;
178                         
179                         // Pass along a fake event
180                         if ( event )
181                                 data.unshift( this.fix({ type: type, target: elem }) );
182
183                         // Enforce the right trigger type
184                         data[0].type = type;
185
186                         // Trigger the event
187                         if ( jQuery.isFunction( jQuery.data(elem, "handle") ) )
188                                 val = jQuery.data(elem, "handle").apply( elem, data );
189
190                         // Handle triggering native .onfoo handlers
191                         if ( !fn && elem["on"+type] && elem["on"+type].apply( elem, data ) === false )
192                                 val = false;
193
194                         // Extra functions don't get the custom event object
195                         if ( event )
196                                 data.shift();
197
198                         // Handle triggering of extra function
199                         if ( extra && jQuery.isFunction( extra ) ) {
200                                 // call the extra function and tack the current return value on the end for possible inspection
201                                 var ret = extra.apply( elem, data.concat( val ) );
202                                 // if anything is returned, give it precedence and have it overwrite the previous value
203                                 if (ret !== undefined)
204                                         val = ret;
205                         }
206
207                         // Trigger the native events (except for clicks on links)
208                         if ( fn && donative !== false && val !== false && !(jQuery.nodeName(elem, 'a') && type == "click") ) {
209                                 this.triggered = true;
210                                 try {
211                                         elem[ type ]();
212                                 // prevent IE from throwing an error for some hidden elements
213                                 } catch (e) {}
214                         }
215
216                         this.triggered = false;
217                 }
218
219                 return val;
220         },
221
222         handle: function(event) {
223                 // returned undefined or false
224                 var val;
225
226                 // Empty object is for triggered events with no data
227                 event = jQuery.event.fix( event || window.event || {} ); 
228
229                 // Namespaced event handlers
230                 var parts = event.type.split(".");
231                 event.type = parts[0];
232
233                 var handlers = jQuery.data(this, "events") && jQuery.data(this, "events")[event.type], args = Array.prototype.slice.call( arguments, 1 );
234                 args.unshift( event );
235
236                 for ( var j in handlers ) {
237                         var handler = handlers[j];
238                         // Pass in a reference to the handler function itself
239                         // So that we can later remove it
240                         args[0].handler = handler;
241                         args[0].data = handler.data;
242
243                         // Filter the functions by class
244                         if ( !parts[1] || handler.type == parts[1] ) {
245                                 var ret = handler.apply( this, args );
246
247                                 if ( val !== false )
248                                         val = ret;
249
250                                 if ( ret === false ) {
251                                         event.preventDefault();
252                                         event.stopPropagation();
253                                 }
254                         }
255                 }
256
257                 // Clean up added properties in IE to prevent memory leak
258                 if (jQuery.browser.msie)
259                         event.target = event.preventDefault = event.stopPropagation =
260                                 event.handler = event.data = null;
261
262                 return val;
263         },
264
265         fix: function(event) {
266                 // Short-circuit if the event has already been fixed by jQuery.event.fix
267                 if ( event[ expando ] )
268                         return event;
269                         
270                 // store a copy of the original event object 
271                 // and clone to set read-only properties
272                 var originalEvent = event;
273                 event = jQuery.extend({}, originalEvent);
274                 
275                 // Mark the event as fixed by jQuery.event.fix
276                 event[ expando ] = true;
277                 
278                 // add preventDefault and stopPropagation since 
279                 // they will not work on the clone
280                 event.preventDefault = function() {
281                         // if preventDefault exists run it on the original event
282                         if (originalEvent.preventDefault)
283                                 originalEvent.preventDefault();
284                         // otherwise set the returnValue property of the original event to false (IE)
285                         originalEvent.returnValue = false;
286                 };
287                 event.stopPropagation = function() {
288                         // if stopPropagation exists run it on the original event
289                         if (originalEvent.stopPropagation)
290                                 originalEvent.stopPropagation();
291                         // otherwise set the cancelBubble property of the original event to true (IE)
292                         originalEvent.cancelBubble = true;
293                 };
294                 
295                 // Fix target property, if necessary
296                 if ( !event.target )
297                         event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either
298                                 
299                 // check if target is a textnode (safari)
300                 if ( event.target.nodeType == 3 )
301                         event.target = originalEvent.target.parentNode;
302
303                 // Add relatedTarget, if necessary
304                 if ( !event.relatedTarget && event.fromElement )
305                         event.relatedTarget = event.fromElement == event.target ? event.toElement : event.fromElement;
306
307                 // Calculate pageX/Y if missing and clientX/Y available
308                 if ( event.pageX == null && event.clientX != null ) {
309                         var doc = document.documentElement, body = document.body;
310                         event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc.clientLeft || 0);
311                         event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc.clientTop || 0);
312                 }
313                         
314                 // Add which for key events
315                 if ( !event.which && (event.charCode || event.keyCode) )
316                         event.which = event.charCode || event.keyCode;
317                 
318                 // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
319                 if ( !event.metaKey && event.ctrlKey )
320                         event.metaKey = event.ctrlKey;
321
322                 // Add which for click: 1 == left; 2 == middle; 3 == right
323                 // Note: button is not normalized, so don't use it
324                 if ( !event.which && event.button )
325                         event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
326                         
327                 return event;
328         },
329         
330         special: {
331                 ready: {
332                         setup: function() {
333                                 // Make sure the ready event is setup
334                                 bindReady();
335                                 return;
336                         },
337                         
338                         teardown: function() { return; }
339                 },
340                 
341                 mouseenter: {
342                         setup: function() {
343                                 if ( jQuery.browser.msie ) return false;
344                                 jQuery(this).bind("mouseover", jQuery.event.special.mouseenter.handler);
345                                 return true;
346                         },
347                 
348                         teardown: function() {
349                                 if ( jQuery.browser.msie ) return false;
350                                 jQuery(this).unbind("mouseover", jQuery.event.special.mouseenter.handler);
351                                 return true;
352                         },
353                         
354                         handler: function(event) {
355                                 // If we actually just moused on to a sub-element, ignore it
356                                 if ( withinElement(event, this) ) return true;
357                                 // Execute the right handlers by setting the event type to mouseenter
358                                 arguments[0].type = "mouseenter";
359                                 return jQuery.event.handle.apply(this, arguments);
360                         }
361                 },
362         
363                 mouseleave: {
364                         setup: function() {
365                                 if ( jQuery.browser.msie ) return false;
366                                 jQuery(this).bind("mouseout", jQuery.event.special.mouseleave.handler);
367                                 return true;
368                         },
369                 
370                         teardown: function() {
371                                 if ( jQuery.browser.msie ) return false;
372                                 jQuery(this).unbind("mouseout", jQuery.event.special.mouseleave.handler);
373                                 return true;
374                         },
375                         
376                         handler: function(event) {
377                                 // If we actually just moused on to a sub-element, ignore it
378                                 if ( withinElement(event, this) ) return true;
379                                 // Execute the right handlers by setting the event type to mouseleave
380                                 arguments[0].type = "mouseleave";
381                                 return jQuery.event.handle.apply(this, arguments);
382                         }
383                 }
384         }
385 };
386
387 jQuery.fn.extend({
388         bind: function( type, data, fn ) {
389                 return type == "unload" ? this.one(type, data, fn) : this.each(function(){
390                         jQuery.event.add( this, type, fn || data, fn && data );
391                 });
392         },
393         
394         one: function( type, data, fn ) {
395                 return this.each(function(){
396                         jQuery.event.add( this, type, function(event) {
397                                 jQuery(this).unbind(event);
398                                 return (fn || data).apply( this, arguments);
399                         }, fn && data);
400                 });
401         },
402
403         unbind: function( type, fn ) {
404                 return this.each(function(){
405                         jQuery.event.remove( this, type, fn );
406                 });
407         },
408
409         trigger: function( type, data, fn ) {
410                 return this.each(function(){
411                         jQuery.event.trigger( type, data, this, true, fn );
412                 });
413         },
414
415         triggerHandler: function( type, data, fn ) {
416                 if ( this[0] )
417                         return jQuery.event.trigger( type, data, this[0], false, fn );
418                 return undefined;
419         },
420
421         toggle: function() {
422                 // Save reference to arguments for access in closure
423                 var args = arguments;
424
425                 return this.click(function(event) {
426                         // Figure out which function to execute
427                         this.lastToggle = 0 == this.lastToggle ? 1 : 0;
428                         
429                         // Make sure that clicks stop
430                         event.preventDefault();
431                         
432                         // and execute the function
433                         return args[this.lastToggle].apply( this, arguments ) || false;
434                 });
435         },
436
437         hover: function(fnOver, fnOut) {
438                 return this.bind('mouseenter', fnOver).bind('mouseleave', fnOut);
439         },
440         
441         ready: function(fn) {
442                 // Attach the listeners
443                 bindReady();
444
445                 // If the DOM is already ready
446                 if ( jQuery.isReady )
447                         // Execute the function immediately
448                         fn.call( document, jQuery );
449                         
450                 // Otherwise, remember the function for later
451                 else
452                         // Add the function to the wait list
453                         jQuery.readyList.push( function() { return fn.call(this, jQuery); } );
454         
455                 return this;
456         }
457 });
458
459 jQuery.extend({
460         isReady: false,
461         readyList: [],
462         // Handle when the DOM is ready
463         ready: function() {
464                 // Make sure that the DOM is not already loaded
465                 if ( !jQuery.isReady ) {
466                         // Remember that the DOM is ready
467                         jQuery.isReady = true;
468                         
469                         // If there are functions bound, to execute
470                         if ( jQuery.readyList ) {
471                                 // Execute all of them
472                                 jQuery.each( jQuery.readyList, function(){
473                                         this.apply( document );
474                                 });
475                                 
476                                 // Reset the list of functions
477                                 jQuery.readyList = null;
478                         }
479                 
480                         // Trigger any bound ready events
481                         $(document).triggerHandler("ready");
482                 }
483         }
484 });
485
486 var readyBound = false;
487
488 function bindReady(){
489         if ( readyBound ) return;
490         readyBound = true;
491
492         // Mozilla, Opera and webkit nightlies currently support this event
493         if ( document.addEventListener )
494                 // Use the handy event callback
495                 document.addEventListener( "DOMContentLoaded", jQuery.ready, false );
496         
497         // If Safari or IE is used
498         // Continually check to see if the document is ready
499         if (jQuery.browser.msie || jQuery.browser.safari ) (function(){
500                 try {
501                         // If IE is used, use the trick by Diego Perini
502                         // http://javascript.nwbox.com/IEContentLoaded/
503                         if ( jQuery.browser.msie || document.readyState != "loaded" && document.readyState != "complete" )
504                                 document.documentElement.doScroll("left");
505                 } catch( error ) {
506                         return setTimeout( arguments.callee, 0 );
507                 }
508
509                 // and execute any waiting functions
510                 jQuery.ready();
511         })();
512
513         // A fallback to window.onload, that will always work
514         jQuery.event.add( window, "load", jQuery.ready );
515 }
516
517 jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
518         "mousedown,mouseup,mousemove,mouseover,mouseout,change,select," + 
519         "submit,keydown,keypress,keyup,error").split(","), function(i, name){
520         
521         // Handle event binding
522         jQuery.fn[name] = function(fn){
523                 return fn ? this.bind(name, fn) : this.trigger(name);
524         };
525 });
526
527 // Checks if an event happened on an element within another element
528 // Used in jQuery.event.special.mouseenter and mouseleave handlers
529 var withinElement = function(event, elem) {
530         // Check if mouse(over|out) are still within the same parent element
531         var parent = event.relatedTarget;
532         // Traverse up the tree
533         while ( parent && parent != elem ) try { parent = parent.parentNode } catch(error) { parent = elem; };
534         // Return true if we actually just moused on to a sub-element
535         return parent == elem;
536 };
537
538 // Prevent memory leaks in IE
539 // And prevent errors on refresh with events like mouseover in other browsers
540 // Window isn't included so as not to unbind existing unload events
541 jQuery(window).bind("unload", function() {
542         jQuery("*").add(document).unbind();
543 });