c0238ccab7256c39ef73cc2b84f9c57e30628d90
[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                 // store a copy of the original event object 
267                 // and clone to set read-only properties
268                 var originalEvent = event;
269                 event = jQuery.extend({}, originalEvent);
270                 
271                 // add preventDefault and stopPropagation since 
272                 // they will not work on the clone
273                 event.preventDefault = function() {
274                         // if preventDefault exists run it on the original event
275                         if (originalEvent.preventDefault)
276                                 originalEvent.preventDefault();
277                         // otherwise set the returnValue property of the original event to false (IE)
278                         originalEvent.returnValue = false;
279                 };
280                 event.stopPropagation = function() {
281                         // if stopPropagation exists run it on the original event
282                         if (originalEvent.stopPropagation)
283                                 originalEvent.stopPropagation();
284                         // otherwise set the cancelBubble property of the original event to true (IE)
285                         originalEvent.cancelBubble = true;
286                 };
287                 
288                 // Fix target property, if necessary
289                 if ( !event.target )
290                         event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either
291                                 
292                 // check if target is a textnode (safari)
293                 if ( event.target.nodeType == 3 )
294                         event.target = originalEvent.target.parentNode;
295
296                 // Add relatedTarget, if necessary
297                 if ( !event.relatedTarget && event.fromElement )
298                         event.relatedTarget = event.fromElement == event.target ? event.toElement : event.fromElement;
299
300                 // Calculate pageX/Y if missing and clientX/Y available
301                 if ( event.pageX == null && event.clientX != null ) {
302                         var doc = document.documentElement, body = document.body;
303                         event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc.clientLeft || 0);
304                         event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc.clientTop || 0);
305                 }
306                         
307                 // Add which for key events
308                 if ( !event.which && (event.charCode || event.keyCode) )
309                         event.which = event.charCode || event.keyCode;
310                 
311                 // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
312                 if ( !event.metaKey && event.ctrlKey )
313                         event.metaKey = event.ctrlKey;
314
315                 // Add which for click: 1 == left; 2 == middle; 3 == right
316                 // Note: button is not normalized, so don't use it
317                 if ( !event.which && event.button )
318                         event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
319                         
320                 return event;
321         },
322         
323         special: {
324                 ready: {
325                         setup: function() {
326                                 // Make sure the ready event is setup
327                                 bindReady();
328                                 return;
329                         },
330                         
331                         teardown: function() { return; }
332                 },
333                 
334                 mouseenter: {
335                         setup: function() {
336                                 if ( jQuery.browser.msie ) return false;
337                                 jQuery(this).bind("mouseover", jQuery.event.special.mouseenter.handler);
338                                 return true;
339                         },
340                 
341                         teardown: function() {
342                                 if ( jQuery.browser.msie ) return false;
343                                 jQuery(this).unbind("mouseover", jQuery.event.special.mouseenter.handler);
344                                 return true;
345                         },
346                         
347                         handler: function(event) {
348                                 // If we actually just moused on to a sub-element, ignore it
349                                 if ( withinElement(event, this) ) return true;
350                                 // Execute the right handlers by setting the event type to mouseenter
351                                 arguments[0].type = "mouseenter";
352                                 return jQuery.event.handle.apply(this, arguments);
353                         }
354                 },
355         
356                 mouseleave: {
357                         setup: function() {
358                                 if ( jQuery.browser.msie ) return false;
359                                 jQuery(this).bind("mouseout", jQuery.event.special.mouseleave.handler);
360                                 return true;
361                         },
362                 
363                         teardown: function() {
364                                 if ( jQuery.browser.msie ) return false;
365                                 jQuery(this).unbind("mouseout", jQuery.event.special.mouseleave.handler);
366                                 return true;
367                         },
368                         
369                         handler: function(event) {
370                                 // If we actually just moused on to a sub-element, ignore it
371                                 if ( withinElement(event, this) ) return true;
372                                 // Execute the right handlers by setting the event type to mouseleave
373                                 arguments[0].type = "mouseleave";
374                                 return jQuery.event.handle.apply(this, arguments);
375                         }
376                 }
377         }
378 };
379
380 jQuery.fn.extend({
381         bind: function( type, data, fn ) {
382                 return type == "unload" ? this.one(type, data, fn) : this.each(function(){
383                         jQuery.event.add( this, type, fn || data, fn && data );
384                 });
385         },
386         
387         one: function( type, data, fn ) {
388                 return this.each(function(){
389                         jQuery.event.add( this, type, function(event) {
390                                 jQuery(this).unbind(event);
391                                 return (fn || data).apply( this, arguments);
392                         }, fn && data);
393                 });
394         },
395
396         unbind: function( type, fn ) {
397                 return this.each(function(){
398                         jQuery.event.remove( this, type, fn );
399                 });
400         },
401
402         trigger: function( type, data, fn ) {
403                 return this.each(function(){
404                         jQuery.event.trigger( type, data, this, true, fn );
405                 });
406         },
407
408         triggerHandler: function( type, data, fn ) {
409                 if ( this[0] )
410                         return jQuery.event.trigger( type, data, this[0], false, fn );
411                 return undefined;
412         },
413
414         toggle: function() {
415                 // Save reference to arguments for access in closure
416                 var args = arguments;
417
418                 return this.click(function(event) {
419                         // Figure out which function to execute
420                         this.lastToggle = 0 == this.lastToggle ? 1 : 0;
421                         
422                         // Make sure that clicks stop
423                         event.preventDefault();
424                         
425                         // and execute the function
426                         return args[this.lastToggle].apply( this, arguments ) || false;
427                 });
428         },
429
430         hover: function(fnOver, fnOut) {
431                 return this.bind('mouseenter', fnOver).bind('mouseleave', fnOut);
432         },
433         
434         ready: function(fn) {
435                 // Attach the listeners
436                 bindReady();
437
438                 // If the DOM is already ready
439                 if ( jQuery.isReady )
440                         // Execute the function immediately
441                         fn.call( document, jQuery );
442                         
443                 // Otherwise, remember the function for later
444                 else
445                         // Add the function to the wait list
446                         jQuery.readyList.push( function() { return fn.call(this, jQuery); } );
447         
448                 return this;
449         }
450 });
451
452 jQuery.extend({
453         isReady: false,
454         readyList: [],
455         // Handle when the DOM is ready
456         ready: function() {
457                 // Make sure that the DOM is not already loaded
458                 if ( !jQuery.isReady ) {
459                         // Remember that the DOM is ready
460                         jQuery.isReady = true;
461                         
462                         // If there are functions bound, to execute
463                         if ( jQuery.readyList ) {
464                                 // Execute all of them
465                                 jQuery.each( jQuery.readyList, function(){
466                                         this.apply( document );
467                                 });
468                                 
469                                 // Reset the list of functions
470                                 jQuery.readyList = null;
471                         }
472                 
473                         // Trigger any bound ready events
474                         $(document).triggerHandler("ready");
475                 }
476         }
477 });
478
479 var readyBound = false;
480
481 function bindReady(){
482         if ( readyBound ) return;
483         readyBound = true;
484
485         // Mozilla, Opera and webkit nightlies currently support this event
486         if ( document.addEventListener )
487                 // Use the handy event callback
488                 document.addEventListener( "DOMContentLoaded", jQuery.ready, false );
489         
490         // If Safari or IE is used
491         // Continually check to see if the document is ready
492         if (jQuery.browser.msie || jQuery.browser.safari ) (function(){
493                 try {
494                         // If IE is used, use the trick by Diego Perini
495                         // http://javascript.nwbox.com/IEContentLoaded/
496                         if ( jQuery.browser.msie || document.readyState != "loaded" && document.readyState != "complete" )
497                                 document.documentElement.doScroll("left");
498                 } catch( error ) {
499                         return setTimeout( arguments.callee, 0 );
500                 }
501
502                 // and execute any waiting functions
503                 jQuery.ready();
504         })();
505
506         // A fallback to window.onload, that will always work
507         jQuery.event.add( window, "load", jQuery.ready );
508 }
509
510 jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
511         "mousedown,mouseup,mousemove,mouseover,mouseout,change,select," + 
512         "submit,keydown,keypress,keyup,error").split(","), function(i, name){
513         
514         // Handle event binding
515         jQuery.fn[name] = function(fn){
516                 return fn ? this.bind(name, fn) : this.trigger(name);
517         };
518 });
519
520 // Checks if an event happened on an element within another element
521 // Used in jQuery.event.special.mouseenter and mouseleave handlers
522 var withinElement = function(event, elem) {
523         // Check if mouse(over|out) are still within the same parent element
524         var parent = event.relatedTarget;
525         // Traverse up the tree
526         while ( parent && parent != elem ) try { parent = parent.parentNode } catch(error) { parent = elem; };
527         // Return true if we actually just moused on to a sub-element
528         return parent == elem;
529 };
530
531 // Prevent memory leaks in IE
532 // And prevent errors on refresh with events like mouseover in other browsers
533 // Window isn't included so as not to unbind existing unload events
534 jQuery(window).bind("unload", function() {
535         jQuery("*").add(document).unbind();
536 });