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