Updating changlog
[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 )
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(this, 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 ) {
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                                 var handler = jQuery.event.special.ready.handler;
327                                 
328                                 // Mozilla, Opera and webkit nightlies currently support this event
329                                 if ( document.addEventListener )
330                                         // Use the handy event callback
331                                         document.addEventListener( "DOMContentLoaded", handler, false );
332         
333                                 // If Safari or IE is used
334                                 // Continually check to see if the document is ready
335                                 if ((jQuery.browser.msie && window == top) || jQuery.browser.safari ) (function(){
336                                         try {
337                                                 // If IE is used, use the trick by Diego Perini
338                                                 // http://javascript.nwbox.com/IEContentLoaded/
339                                                 if ( jQuery.browser.msie || document.readyState != "loaded" && document.readyState != "complete" )
340                                                         document.documentElement.doScroll("left");
341                                         } catch( error ) {
342                                                 setTimeout( arguments.callee, 0 );
343                                                 return;
344                                         }
345
346                                         // and execute any waiting functions
347                                         handler();
348                                 })();
349
350                                 // A fallback to window.onload, that will always work
351                                 jQuery.event.add( window, "load", handler );
352                         },
353                         
354                         teardown: function() {return;},
355                         
356                         handler: function() {
357                                 // Make sure that the DOM is not already loaded
358                                 if ( !jQuery.isReady ) {
359                                         // Remember that the DOM is ready
360                                         jQuery.isReady = true;
361                                         jQuery(document).triggerHandler("ready");
362                                         jQuery(document).unbind("ready");
363                                 }
364                         }
365                 },
366                 
367                 mouseenter: {
368                         setup: function() {
369                                 if ( jQuery.browser.msie ) return false;
370                                 jQuery(this).bind("mouseover", jQuery.event.special.mouseenter.handler);
371                                 return true;
372                         },
373                 
374                         teardown: function() {
375                                 if ( jQuery.browser.msie ) return false;
376                                 jQuery(this).unbind("mouseover", jQuery.event.special.mouseenter.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 mouseenter
384                                 arguments[0].type = "mouseenter";
385                                 return jQuery.event.handle.apply(this, arguments);
386                         }
387                 },
388         
389                 mouseleave: {
390                         setup: function() {
391                                 if ( jQuery.browser.msie ) return false;
392                                 jQuery(this).bind("mouseout", jQuery.event.special.mouseleave.handler);
393                                 return true;
394                         },
395                 
396                         teardown: function() {
397                                 if ( jQuery.browser.msie ) return false;
398                                 jQuery(this).unbind("mouseout", jQuery.event.special.mouseleave.handler);
399                                 return true;
400                         },
401                         
402                         handler: function(event) {
403                                 // If we actually just moused on to a sub-element, ignore it
404                                 if ( withinElement(event, this) ) return true;
405                                 // Execute the right handlers by setting the event type to mouseleave
406                                 arguments[0].type = "mouseleave";
407                                 return jQuery.event.handle.apply(this, arguments);
408                         }
409                 }
410         }
411 };
412
413 jQuery.fn.extend({
414         bind: function( type, data, fn ) {
415                 return type == "unload" ? this.one(type, data, fn) : this.each(function(){
416                         jQuery.event.add( this, type, fn || data, fn && data );
417                 });
418         },
419         
420         one: function( type, data, fn ) {
421                 return this.each(function(){
422                         jQuery.event.add( this, type, function(event) {
423                                 jQuery(this).unbind(event);
424                                 return (fn || data).apply( this, arguments);
425                         }, fn && data);
426                 });
427         },
428
429         unbind: function( type, fn ) {
430                 return this.each(function(){
431                         jQuery.event.remove( this, type, fn );
432                 });
433         },
434
435         trigger: function( type, data, fn ) {
436                 return this.each(function(){
437                         jQuery.event.trigger( type, data, this, true, fn );
438                 });
439         },
440
441         triggerHandler: function( type, data, fn ) {
442                 if ( this[0] )
443                         return jQuery.event.trigger( type, data, this[0], false, fn );
444                 return undefined;
445         },
446
447         toggle: function() {
448                 // Save reference to arguments for access in closure
449                 var args = arguments;
450
451                 return this.click(function(event) {
452                         // Figure out which function to execute
453                         this.lastToggle = 0 == this.lastToggle ? 1 : 0;
454                         
455                         // Make sure that clicks stop
456                         event.preventDefault();
457                         
458                         // and execute the function
459                         return args[this.lastToggle].apply( this, arguments ) || false;
460                 });
461         },
462
463         hover: function(fnOver, fnOut) {
464                 return this.bind('mouseenter', fnOver).bind('mouseleave', fnOut);
465         }
466 });
467
468 jQuery.extend({
469         isReady: false
470 });
471
472 jQuery.each( ("blur,focus,load,ready,resize,scroll,unload,click,dblclick," +
473         "mousedown,mouseup,mousemove,mouseover,mouseout,change,select," + 
474         "submit,keydown,keypress,keyup,error").split(","), function(i, name){
475         
476         // Handle event binding
477         jQuery.fn[name] = function(fn){
478                 return fn ? this.bind(name, fn) : this.trigger(name);
479         };
480 });
481
482 // Checks if an event happened on an element within another element
483 // Used in jQuery.event.special.mouseenter and mouseleave handlers
484 var withinElement = function(event, elem) {
485         // Check if mouse(over|out) are still within the same parent element
486         var parent = event.relatedTarget;
487         // Traverse up the tree
488         while ( parent && parent != elem ) try { parent = parent.parentNode } catch(error) { parent = elem; };
489         // Return true if we actually just moused on to a sub-element
490         return parent == elem;
491 };
492
493 // Prevent memory leaks in IE
494 // And prevent errors on refresh with events like mouseover in other browsers
495 // Window isn't included so as not to unbind existing unload events
496 jQuery(window).bind("unload", function() {
497         jQuery("*").add(document).unbind();
498 });