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.
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 )
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 )
19 // Make sure that the function being executed has a unique ID
21 handler.guid = this.guid++;
23 // if data is passed, bind to handler
24 if( data != undefined ) {
25 // Create temporary function pointer to original handler
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);
34 // Store data in unique handler
37 // Set the guid of unique handler to the same of original handler, so it can be removed
38 handler.guid = fn.guid;
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
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 )
52 val = jQuery.event.handle.apply(arguments.callee.elem, arguments);
56 // Add elem as a property of the handle function
57 // This is to prevent a memory leak with non-native
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(".");
67 handler.type = parts[1];
69 // Get the current list of functions bound to this event
70 var handlers = events[type];
72 // Init the event handler queue
74 handlers = events[type] = {};
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);
88 // Add the function to the element's handler list
89 handlers[handler.guid] = handler;
91 // Keep track of which events have been used, for global triggering
92 jQuery.event.global[type] = true;
95 // Nullify elem to prevent memory leaks in IE
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 )
108 var events = jQuery.data(elem, "events"), ret, index;
111 // Unbind all events for the element
112 if ( types == undefined )
113 for ( var type in events )
114 this.remove( elem, type );
116 // types is actually an event object here
118 handler = types.handler;
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(".");
129 if ( events[type] ) {
130 // remove the given handler for the given type
132 delete events[type][handler.guid];
134 // remove all handlers for the given type
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];
141 // remove generic event handler if no more handlers exist
142 for ( ret in events[type] ) break;
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"));
157 // Remove the expando if it's no longer used
158 for ( ret in events ) break;
160 var handle = jQuery.data( elem, "handle" );
161 if ( handle ) handle.elem = null;
162 jQuery.removeData( elem, "events" );
163 jQuery.removeData( elem, "handle" );
168 trigger: function(type, data, elem, donative, extra) {
169 // Clone the incoming data, if any
170 data = jQuery.makeArray(data || []);
172 // Handle a global trigger
174 // Only trigger if we've ever bound an event for it
175 if ( this.global[type] )
176 jQuery("*").add([window, document]).trigger(type, data);
178 // Handle triggering a single element
180 // don't do events on text and comment nodes
181 if ( elem.nodeType == 3 || elem.nodeType == 8 )
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;
188 // Pass along a fake event
190 data.unshift( this.fix({ type: type, target: elem }) );
192 // Enforce the right trigger type
196 if ( jQuery.isFunction( jQuery.data(elem, "handle") ) )
197 val = jQuery.data(elem, "handle").apply( elem, data );
199 // Handle triggering native .onfoo handlers
200 if ( !fn && elem["on"+type] && elem["on"+type].apply( elem, data ) === false )
203 // Extra functions don't get the custom event object
207 // Handle triggering of extra function
208 if ( extra && jQuery.isFunction( extra ) ) {
209 // call the extra function and tack the current return value on the end for possible inspection
210 ret = extra.apply( elem, val == null ? data : data.concat( val ) );
211 // if anything is returned, give it precedence and have it overwrite the previous value
212 if (ret !== undefined)
216 // Trigger the native events (except for clicks on links)
217 if ( fn && donative !== false && val !== false && !(jQuery.nodeName(elem, 'a') && type == "click") ) {
218 this.triggered = true;
221 // prevent IE from throwing an error for some hidden elements
225 this.triggered = false;
231 handle: function(event) {
232 // returned undefined or false
235 // Empty object is for triggered events with no data
236 event = jQuery.event.fix( event || window.event || {} );
238 // Namespaced event handlers
239 var parts = event.type.split(".");
240 event.type = parts[0];
242 var handlers = jQuery.data(this, "events") && jQuery.data(this, "events")[event.type], args = Array.prototype.slice.call( arguments, 1 );
243 args.unshift( event );
245 for ( var j in handlers ) {
246 var handler = handlers[j];
247 // Pass in a reference to the handler function itself
248 // So that we can later remove it
249 args[0].handler = handler;
250 args[0].data = handler.data;
252 // Filter the functions by class
253 if ( !parts[1] || handler.type == parts[1] ) {
254 var ret = handler.apply( this, args );
259 if ( ret === false ) {
260 event.preventDefault();
261 event.stopPropagation();
266 // Clean up added properties in IE to prevent memory leak
267 if (jQuery.browser.msie)
268 event.target = event.preventDefault = event.stopPropagation =
269 event.handler = event.data = null;
274 fix: function(event) {
275 // store a copy of the original event object
276 // and clone to set read-only properties
277 var originalEvent = event;
278 event = jQuery.extend({}, originalEvent);
280 // add preventDefault and stopPropagation since
281 // they will not work on the clone
282 event.preventDefault = function() {
283 // if preventDefault exists run it on the original event
284 if (originalEvent.preventDefault)
285 originalEvent.preventDefault();
286 // otherwise set the returnValue property of the original event to false (IE)
287 originalEvent.returnValue = false;
289 event.stopPropagation = function() {
290 // if stopPropagation exists run it on the original event
291 if (originalEvent.stopPropagation)
292 originalEvent.stopPropagation();
293 // otherwise set the cancelBubble property of the original event to true (IE)
294 originalEvent.cancelBubble = true;
297 // Fix target property, if necessary
299 event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either
301 // check if target is a textnode (safari)
302 if ( event.target.nodeType == 3 )
303 event.target = originalEvent.target.parentNode;
305 // Add relatedTarget, if necessary
306 if ( !event.relatedTarget && event.fromElement )
307 event.relatedTarget = event.fromElement == event.target ? event.toElement : event.fromElement;
309 // Calculate pageX/Y if missing and clientX/Y available
310 if ( event.pageX == null && event.clientX != null ) {
311 var doc = document.documentElement, body = document.body;
312 event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc.clientLeft || 0);
313 event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc.clientTop || 0);
316 // Add which for key events
317 if ( !event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode) )
318 event.which = event.charCode || event.keyCode;
320 // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
321 if ( !event.metaKey && event.ctrlKey )
322 event.metaKey = event.ctrlKey;
324 // Add which for click: 1 == left; 2 == middle; 3 == right
325 // Note: button is not normalized, so don't use it
326 if ( !event.which && event.button )
327 event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
335 // Make sure the ready event is setup
340 teardown: function() { return; }
345 if ( jQuery.browser.msie ) return false;
346 jQuery(this).bind("mouseover", jQuery.event.special.mouseenter.handler);
350 teardown: function() {
351 if ( jQuery.browser.msie ) return false;
352 jQuery(this).unbind("mouseover", jQuery.event.special.mouseenter.handler);
356 handler: function(event) {
357 // If we actually just moused on to a sub-element, ignore it
358 if ( withinElement(event, this) ) return true;
359 // Execute the right handlers by setting the event type to mouseenter
360 arguments[0].type = "mouseenter";
361 return jQuery.event.handle.apply(this, arguments);
367 if ( jQuery.browser.msie ) return false;
368 jQuery(this).bind("mouseout", jQuery.event.special.mouseleave.handler);
372 teardown: function() {
373 if ( jQuery.browser.msie ) return false;
374 jQuery(this).unbind("mouseout", jQuery.event.special.mouseleave.handler);
378 handler: function(event) {
379 // If we actually just moused on to a sub-element, ignore it
380 if ( withinElement(event, this) ) return true;
381 // Execute the right handlers by setting the event type to mouseleave
382 arguments[0].type = "mouseleave";
383 return jQuery.event.handle.apply(this, arguments);
390 bind: function( type, data, fn ) {
391 return type == "unload" ? this.one(type, data, fn) : this.each(function(){
392 jQuery.event.add( this, type, fn || data, fn && data );
396 one: function( type, data, fn ) {
397 return this.each(function(){
398 jQuery.event.add( this, type, function(event) {
399 jQuery(this).unbind(event);
400 return (fn || data).apply( this, arguments);
405 unbind: function( type, fn ) {
406 return this.each(function(){
407 jQuery.event.remove( this, type, fn );
411 trigger: function( type, data, fn ) {
412 return this.each(function(){
413 jQuery.event.trigger( type, data, this, true, fn );
417 triggerHandler: function( type, data, fn ) {
419 return jQuery.event.trigger( type, data, this[0], false, fn );
424 // Save reference to arguments for access in closure
425 var args = arguments;
427 return this.click(function(event) {
428 // Figure out which function to execute
429 this.lastToggle = 0 == this.lastToggle ? 1 : 0;
431 // Make sure that clicks stop
432 event.preventDefault();
434 // and execute the function
435 return args[this.lastToggle].apply( this, arguments ) || false;
439 hover: function(fnOver, fnOut) {
440 return this.bind('mouseenter', fnOver).bind('mouseleave', fnOut);
443 ready: function(fn) {
444 // Attach the listeners
447 // If the DOM is already ready
448 if ( jQuery.isReady )
449 // Execute the function immediately
450 fn.call( document, jQuery );
452 // Otherwise, remember the function for later
454 // Add the function to the wait list
455 jQuery.readyList.push( function() { return fn.call(this, jQuery); } );
464 // Handle when the DOM is ready
466 // Make sure that the DOM is not already loaded
467 if ( !jQuery.isReady ) {
468 // Remember that the DOM is ready
469 jQuery.isReady = true;
471 // If there are functions bound, to execute
472 if ( jQuery.readyList ) {
473 // Execute all of them
474 jQuery.each( jQuery.readyList, function(){
475 this.apply( document );
478 // Reset the list of functions
479 jQuery.readyList = null;
482 // Trigger any bound ready events
483 jQuery(document).triggerHandler("ready");
488 var readyBound = false;
490 function bindReady(){
491 if ( readyBound ) return;
494 // Mozilla, Opera (see further below for it) and webkit nightlies currently support this event
495 if ( document.addEventListener && !jQuery.browser.opera)
496 // Use the handy event callback
497 document.addEventListener( "DOMContentLoaded", jQuery.ready, false );
499 // If IE is used and is not in a frame
500 // Continually check to see if the document is ready
501 if ( jQuery.browser.msie && window == top ) (function(){
502 if (jQuery.isReady) return;
504 // If IE is used, use the trick by Diego Perini
505 // http://javascript.nwbox.com/IEContentLoaded/
506 document.documentElement.doScroll("left");
508 setTimeout( arguments.callee, 0 );
511 // and execute any waiting functions
515 if ( jQuery.browser.opera )
516 document.addEventListener( "DOMContentLoaded", function () {
517 if (jQuery.isReady) return;
518 for (var i = 0; i < document.styleSheets.length; i++)
519 if (document.styleSheets[i].disabled) {
520 setTimeout( arguments.callee, 0 );
523 // and execute any waiting functions
527 if ( jQuery.browser.safari ) {
530 if (jQuery.isReady) return;
531 if ( document.readyState != "loaded" && document.readyState != "complete" ) {
532 setTimeout( arguments.callee, 0 );
535 if ( numStyles === undefined )
536 numStyles = jQuery("style, link[rel=stylesheet]").length;
537 if ( document.styleSheets.length != numStyles ) {
538 setTimeout( arguments.callee, 0 );
541 // and execute any waiting functions
546 // A fallback to window.onload, that will always work
547 jQuery.event.add( window, "load", jQuery.ready );
550 jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
551 "mousedown,mouseup,mousemove,mouseover,mouseout,change,select," +
552 "submit,keydown,keypress,keyup,error").split(","), function(i, name){
554 // Handle event binding
555 jQuery.fn[name] = function(fn){
556 return fn ? this.bind(name, fn) : this.trigger(name);
560 // Checks if an event happened on an element within another element
561 // Used in jQuery.event.special.mouseenter and mouseleave handlers
562 var withinElement = function(event, elem) {
563 // Check if mouse(over|out) are still within the same parent element
564 var parent = event.relatedTarget;
565 // Traverse up the tree
566 while ( parent && parent != elem ) try { parent = parent.parentNode; } catch(error) { parent = elem; }
567 // Return true if we actually just moused on to a sub-element
568 return parent == elem;
571 // Prevent memory leaks in IE
572 // And prevent errors on refresh with events like mouseover in other browsers
573 // Window isn't included so as not to unbind existing unload events
574 jQuery(window).bind("unload", function() {
575 jQuery("*").add(document).unbind();