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