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