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