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