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