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.
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 ) {
15 // For whatever reason, IE has trouble passing the window object
16 // around, causing it to be cloned in the process
17 if ( elem.setInterval && ( elem !== window && !elem.frameElement ) ) {
21 // Make sure that the function being executed has a unique ID
22 if ( !handler.guid ) {
23 handler.guid = this.guid++;
26 // if data is passed, bind to handler
27 if ( data !== undefined ) {
28 // Create temporary function pointer to original handler
31 // Create unique handler function, wrapped around original handler
32 handler = this.proxy( fn );
34 // Store data in unique handler
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 ) :
47 // Add elem as a property of the handle function
48 // This is to prevent a memory leak with non-native
52 // Handle multiple events separated by a space
53 // jQuery(...).bind("mouseover mouseout", fn);
54 types = types.split( /\s+/ );
56 while ( (type = types[ i++ ]) ) {
57 // Namespaced event handlers
58 var namespaces = type.split(".");
59 type = namespaces.shift();
60 handler.type = namespaces.slice().sort().join(".");
62 // Get the current list of functions bound to this event
63 var handlers = events[ type ],
64 special = this.special[ type ] || {};
67 var modifiedHandler = special.add.call( elem, handler, data, namespaces );
68 if ( modifiedHandler && jQuery.isFunction( modifiedHandler ) ) {
69 modifiedHandler.guid = modifiedHandler.guid || handler.guid;
70 handler = modifiedHandler;
74 // Init the event handler queue
76 handlers = events[ type ] = {};
78 // Check for a special event handler
79 // Only use addEventListener/attachEvent if the special
80 // events handler returns false
81 if ( !special.setup || special.setup.call( elem, data, namespaces ) === false ) {
82 // Bind the global event handler to the element
83 if ( elem.addEventListener ) {
84 elem.addEventListener( type, handle, false );
85 } else if ( elem.attachEvent ) {
86 elem.attachEvent( "on" + type, handle );
91 // Add the function to the element's handler list
92 handlers[ handler.guid ] = handler;
94 // Keep track of which events have been used, for global triggering
95 this.global[ type ] = true;
98 // Nullify elem to prevent memory leaks in IE
105 // Detach an event or set of events from an element
106 remove: function( elem, types, handler ) {
107 // don't do events on text and comment nodes
108 if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
112 var events = jQuery.data( elem, "events" ), ret, type;
115 // Unbind all events for the element
116 if ( types === undefined || (typeof types === "string" && types.charAt(0) === ".") ) {
117 for ( type in events ) {
118 this.remove( elem, type + (types || "") );
121 // types is actually an event object here
123 handler = types.handler;
127 // Handle multiple events seperated by a space
128 // jQuery(...).unbind("mouseover mouseout", fn);
129 types = types.split(/\s+/);
131 while ( (type = types[ i++ ]) ) {
132 // Namespaced event handlers
133 var namespaces = type.split(".");
134 type = namespaces.shift();
135 var all = !namespaces.length,
136 namespace = new RegExp("(^|\\.)" + namespaces.slice().sort().join(".*\\.") + "(\\.|$)"),
137 special = this.special[ type ] || {};
139 if ( events[ type ] ) {
140 // remove the given handler for the given type
142 delete events[ type ][ handler.guid ];
144 // remove all handlers for the given type
146 for ( var handle in events[ type ] ) {
147 // Handle the removal of namespaced events
148 if ( all || namespace.test( events[ type ][ handle ].type ) ) {
149 delete events[ type ][ handle ];
154 if ( special.remove ) {
155 special.remove.call( elem, namespaces );
158 // remove generic event handler if no more handlers exist
159 for ( ret in events[ type ] ) {
163 if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) {
164 if ( elem.removeEventListener ) {
165 elem.removeEventListener( type, jQuery.data( elem, "handle" ), false );
166 } else if ( elem.detachEvent ) {
167 elem.detachEvent( "on" + type, jQuery.data( elem, "handle" ) );
171 delete events[ type ];
177 // Remove the expando if it's no longer used
178 for ( ret in events ) {
182 var handle = jQuery.data( elem, "handle" );
186 jQuery.removeData( elem, "events" );
187 jQuery.removeData( elem, "handle" );
192 // bubbling is internal
193 trigger: function( event, data, elem /*, bubbling */ ) {
194 // Event object or event type
195 var type = event.type || event,
196 bubbling = arguments[3];
199 event = typeof event === "object" ?
200 // jQuery.Event object
201 event[expando] ? event :
203 jQuery.extend( jQuery.Event(type), event ) :
204 // Just the event type (string)
207 if ( type.indexOf("!") >= 0 ) {
208 event.type = type = type.slice(0, -1);
209 event.exclusive = true;
212 // Handle a global trigger
214 // Don't bubble custom events when global (to avoid too much overhead)
215 event.stopPropagation();
216 // Only trigger if we've ever bound an event for it
217 if ( this.global[ type ] ) {
218 jQuery.each( jQuery.cache, function() {
219 if ( this.events && this.events[type] ) {
220 jQuery.event.trigger( event, data, this.handle.elem );
226 // Handle triggering a single element
228 // don't do events on text and comment nodes
229 if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) {
233 // Clean up in case it is reused
234 event.result = undefined;
237 // Clone the incoming data, if any
238 data = jQuery.makeArray( data );
239 data.unshift( event );
242 event.currentTarget = elem;
244 // Trigger the event, it is assumed that "handle" is a function
245 var handle = jQuery.data( elem, "handle" );
247 handle.apply( elem, data );
250 var nativeFn, nativeHandler;
252 nativeFn = elem[ type ];
253 nativeHandler = elem[ "on" + type ];
254 // prevent IE from throwing an error for some elements with some event types, see #3533
256 // Handle triggering native .onfoo handlers (and on links since we don't call .click() for links)
257 if ( (!nativeFn || (jQuery.nodeName(elem, 'a') && type === "click")) && nativeHandler && nativeHandler.apply( elem, data ) === false ) {
258 event.result = false;
261 // Trigger the native events (except for clicks on links)
262 if ( !bubbling && nativeFn && !event.isDefaultPrevented() && !(jQuery.nodeName(elem, 'a') && type === "click") ) {
263 this.triggered = true;
266 // prevent IE from throwing an error for some hidden elements
270 this.triggered = false;
272 if ( !event.isPropagationStopped() ) {
273 var parent = elem.parentNode || elem.ownerDocument;
275 jQuery.event.trigger( event, data, parent, true );
280 handle: function( event ) {
281 // returned undefined or false
284 event = arguments[0] = jQuery.event.fix( event || window.event );
285 event.currentTarget = this;
287 // Namespaced event handlers
288 var namespaces = event.type.split(".");
289 event.type = namespaces.shift();
291 // Cache this now, all = true means, any handler
292 all = !namespaces.length && !event.exclusive;
294 var namespace = new RegExp("(^|\\.)" + namespaces.slice().sort().join(".*\\.") + "(\\.|$)");
296 handlers = ( jQuery.data(this, "events") || {} )[ event.type ];
298 for ( var j in handlers ) {
299 var handler = handlers[ j ];
301 // Filter the functions by class
302 if ( all || namespace.test(handler.type) ) {
303 // Pass in a reference to the handler function itself
304 // So that we can later remove it
305 event.handler = handler;
306 event.data = handler.data;
308 var ret = handler.apply( this, arguments );
310 if ( ret !== undefined ) {
312 if ( ret === false ) {
313 event.preventDefault();
314 event.stopPropagation();
318 if ( event.isImmediatePropagationStopped() ) {
326 props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
328 fix: function( event ) {
329 if ( event[ expando ] ) {
333 // store a copy of the original event object
334 // and "clone" to set read-only properties
335 var originalEvent = event;
336 event = jQuery.Event( originalEvent );
338 for ( var i = this.props.length, prop; i; ) {
339 prop = this.props[ --i ];
340 event[ prop ] = originalEvent[ prop ];
343 // Fix target property, if necessary
344 if ( !event.target ) {
345 event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either
348 // check if target is a textnode (safari)
349 if ( event.target.nodeType === 3 ) {
350 event.target = event.target.parentNode;
353 // Add relatedTarget, if necessary
354 if ( !event.relatedTarget && event.fromElement ) {
355 event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement;
358 // Calculate pageX/Y if missing and clientX/Y available
359 if ( event.pageX == null && event.clientX != null ) {
360 var doc = document.documentElement, body = document.body;
361 event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
362 event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
365 // Add which for key events
366 if ( !event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode) ) {
367 event.which = event.charCode || event.keyCode;
370 // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
371 if ( !event.metaKey && event.ctrlKey ) {
372 event.metaKey = event.ctrlKey;
375 // Add which for click: 1 == left; 2 == middle; 3 == right
376 // Note: button is not normalized, so don't use it
377 if ( !event.which && event.button !== undefined ) {
378 event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
384 proxy: function( fn, proxy, thisObject ) {
385 if ( proxy !== undefined && !jQuery.isFunction( proxy ) ) {
389 // FIXME: Should proxy be redefined to be applied with thisObject if defined?
390 proxy = proxy || function() { return fn.apply( thisObject !== undefined ? thisObject : this, arguments ); };
391 // Set the guid of unique handler to the same of original handler, so it can be removed
392 proxy.guid = fn.guid = fn.guid || proxy.guid || this.guid++;
393 // So proxy can be declared as an argument
399 // Make sure the ready event is setup
401 teardown: function() {}
405 add: function( proxy, data, namespaces ) {
406 jQuery.extend( proxy, data || {} );
407 proxy.guid += data.selector + data.live;
408 jQuery.event.add( this, data.live, liveHandler );
411 remove: function( namespaces ) {
412 if ( namespaces.length ) {
413 var remove = 0, name = new RegExp("(^|\\.)" + namespaces[0] + "(\\.|$)");
415 jQuery.each( (jQuery.data(this, "events").live || {}), function() {
416 if ( name.test(this.type) ) {
422 jQuery.event.remove( this, namespaces[0], liveHandler );
430 jQuery.Event = function( src ){
431 // Allow instantiation without the 'new' keyword
432 if ( !this.preventDefault ) {
433 return new jQuery.Event( src );
437 if ( src && src.type ) {
438 this.originalEvent = src;
439 this.type = src.type;
445 // timeStamp is buggy for some events on Firefox(#3843)
446 // So we won't rely on the native value
447 this.timeStamp = now();
450 this[ expando ] = true;
453 function returnFalse() {
456 function returnTrue() {
460 // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
461 // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
462 jQuery.Event.prototype = {
463 preventDefault: function() {
464 this.isDefaultPrevented = returnTrue;
466 var e = this.originalEvent;
470 // if preventDefault exists run it on the original event
471 if ( e.preventDefault ) {
474 // otherwise set the returnValue property of the original event to false (IE)
475 e.returnValue = false;
477 stopPropagation: function() {
478 this.isPropagationStopped = returnTrue;
480 var e = this.originalEvent;
484 // if stopPropagation exists run it on the original event
485 if ( e.stopPropagation ) {
488 // otherwise set the cancelBubble property of the original event to true (IE)
489 e.cancelBubble = true;
491 stopImmediatePropagation: function(){
492 this.isImmediatePropagationStopped = returnTrue;
493 this.stopPropagation();
495 isDefaultPrevented: returnFalse,
496 isPropagationStopped: returnFalse,
497 isImmediatePropagationStopped: returnFalse
499 // Checks if an event happened on an element within another element
500 // Used in jQuery.event.special.mouseenter and mouseleave handlers
501 var withinElement = function( event ) {
502 // Check if mouse(over|out) are still within the same parent element
503 var parent = event.relatedTarget;
504 // Traverse up the tree
505 while ( parent && parent != this ) {
506 // Firefox sometimes assigns relatedTarget a XUL element
507 // which we cannot access the parentNode property of
508 try { parent = parent.parentNode; }
509 // assuming we've left the element since we most likely mousedover a xul element
513 if ( parent != this ) {
514 // set the correct event type
515 event.type = event.data;
516 // handle event if we actually just moused on to a non sub-element
517 jQuery.event.handle.apply( this, arguments );
522 mouseover: 'mouseenter',
523 mouseout: 'mouseleave'
524 }, function( orig, fix ) {
525 jQuery.event.special[ fix ] = {
527 jQuery.event.add( this, orig, withinElement, fix );
529 teardown: function(){
530 jQuery.event.remove( this, orig, withinElement );
536 bind: function( type, data, fn, thisObject ) {
537 if ( jQuery.isFunction( data ) ) {
538 if ( fn !== undefined ) {
544 fn = thisObject === undefined ? fn : jQuery.event.proxy( fn, thisObject );
545 return type === "unload" ? this.one(type, data, fn, thisObject) : this.each(function() {
546 jQuery.event.add( this, type, fn, data );
550 one: function( type, data, fn, thisObject ) {
551 if ( jQuery.isFunction( data ) ) {
552 if ( fn !== undefined ) {
558 fn = thisObject === undefined ? fn : jQuery.event.proxy( fn, thisObject );
559 var one = jQuery.event.proxy( fn, function( event ) {
560 jQuery( this ).unbind( event, one );
561 return fn.apply( this, arguments );
563 return this.each(function() {
564 jQuery.event.add( this, type, one, data );
568 unbind: function( type, fn ) {
569 return this.each(function() {
570 jQuery.event.remove( this, type, fn );
574 trigger: function( type, data ) {
575 return this.each(function() {
576 jQuery.event.trigger( type, data, this );
580 triggerHandler: function( type, data ) {
582 var event = jQuery.Event( type );
583 event.preventDefault();
584 event.stopPropagation();
585 jQuery.event.trigger( event, data, this[0] );
590 toggle: function( fn ) {
591 // Save reference to arguments for access in closure
592 var args = arguments, i = 1;
594 // link all the functions, so any of them can unbind this click handler
595 while( i < args.length ) {
596 jQuery.event.proxy( fn, args[ i++ ] );
599 return this.click( jQuery.event.proxy( fn, function( event ) {
600 // Figure out which function to execute
601 this.lastToggle = ( this.lastToggle || 0 ) % i;
603 // Make sure that clicks stop
604 event.preventDefault();
606 // and execute the function
607 return args[ this.lastToggle++ ].apply( this, arguments ) || false;
611 hover: function( fnOver, fnOut ) {
612 return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
615 ready: function( fn ) {
616 // Attach the listeners
619 // If the DOM is already ready
620 if ( jQuery.isReady ) {
621 // Execute the function immediately
622 fn.call( document, jQuery );
624 // Otherwise, remember the function for later
626 // Add the function to the wait list
627 jQuery.readyList.push( fn );
633 live: function( type, data, fn, thisObject ) {
634 if ( jQuery.isFunction( data ) ) {
635 if ( fn !== undefined ) {
641 jQuery( this.context ).bind( liveConvert( type, this.selector ), {
642 data: data, selector: this.selector, live: type
647 die: function( type, fn ) {
648 jQuery( this.context ).unbind( liveConvert( type, this.selector ), fn ? { guid: fn.guid + this.selector + type } : null );
653 function liveHandler( event ) {
654 var stop = true, elems = [], args = arguments;
656 jQuery.each( jQuery.data( this, "events" ).live || [], function( i, fn ) {
657 if ( fn.live === event.type ) {
658 var elem = jQuery( event.target ).closest( fn.selector )[0];
660 elems.push({ elem: elem, fn: fn });
665 elems.sort(function( a, b ) {
666 return jQuery.data( a.elem, "closest" ) - jQuery.data( b.elem, "closest" );
669 jQuery.each(elems, function() {
670 event.currentTarget = this.elem;
671 event.data = this.fn.data;
672 if ( this.fn.apply( this.elem, args ) === false ) {
673 return (stop = false);
680 function liveConvert( type, selector ) {
681 return ["live", type, selector.replace(/\./g, "`").replace(/ /g, "|")].join(".");
687 // Handle when the DOM is ready
689 // Make sure that the DOM is not already loaded
690 if ( !jQuery.isReady ) {
691 // Remember that the DOM is ready
692 jQuery.isReady = true;
694 // If there are functions bound, to execute
695 if ( jQuery.readyList ) {
696 // Execute all of them
698 while ( (fn = jQuery.readyList[ i++ ]) ) {
699 fn.call( document, jQuery );
702 // Reset the list of functions
703 jQuery.readyList = null;
706 // Trigger any bound ready events
707 jQuery( document ).triggerHandler( "ready" );
712 var readyBound = false;
714 function bindReady() {
715 if ( readyBound ) return;
718 // Mozilla, Opera and webkit nightlies currently support this event
719 if ( document.addEventListener ) {
720 // Use the handy event callback
721 document.addEventListener( "DOMContentLoaded", function() {
722 document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
726 // If IE event model is used
727 } else if ( document.attachEvent ) {
728 // ensure firing before onload,
729 // maybe late but safe also for iframes
730 document.attachEvent("onreadystatechange", function() {
731 if ( document.readyState === "complete" ) {
732 document.detachEvent( "onreadystatechange", arguments.callee );
737 // If IE and not an iframe
738 // continually check to see if the document is ready
739 if ( document.documentElement.doScroll && window === window.top ) (function() {
740 if ( jQuery.isReady ) {
745 // If IE is used, use the trick by Diego Perini
746 // http://javascript.nwbox.com/IEContentLoaded/
747 document.documentElement.doScroll("left");
749 setTimeout( arguments.callee, 0 );
753 // and execute any waiting functions
758 // A fallback to window.onload, that will always work
759 jQuery.event.add( window, "load", jQuery.ready );
762 jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
763 "mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave," +
764 "change,select,submit,keydown,keypress,keyup,error").split(","), function( i, name ) {
766 // Handle event binding
767 jQuery.fn[ name ] = function( fn ) {
768 return fn ? this.bind( name, fn ) : this.trigger( name );
772 // Prevent memory leaks in IE
773 // And prevent errors on refresh with events like mouseover in other browsers
774 // Window isn't included so as not to unbind existing unload events
776 // - http://isaacschlueter.com/2006/10/msie-memory-leaks/
777 // - https://bugzilla.mozilla.org/show_bug.cgi?id=252542
778 jQuery( window ).bind( 'unload', function() {
779 for ( var id in jQuery.cache ) {
781 if ( id != 1 && jQuery.cache[ id ].handle ) {
782 jQuery.event.remove( jQuery.cache[ id ].handle.elem );