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 = 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 ( !this.special[ type ] || this.special[ type ].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;
198 event = typeof event === "object" ?
199 // jQuery.Event object
200 event[expando] ? event :
202 jQuery.extend( jQuery.Event(type), event ) :
203 // Just the event type (string)
206 if ( type.indexOf("!") >= 0 ) {
207 event.type = type = type.slice(0, -1);
208 event.exclusive = true;
211 // Handle a global trigger
213 // Don't bubble custom events when global (to avoid too much overhead)
214 event.stopPropagation();
215 // Only trigger if we've ever bound an event for it
216 if ( this.global[ type ] ) {
217 for ( var cached in jQuery.cache ) {
218 if ( cached.events && cached.events[ type ] ) {
219 this.trigger( event, data, cached.handle.elem );
225 // Handle triggering a single element
227 // don't do events on text and comment nodes
228 if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) {
232 // Clean up in case it is reused
233 event.result = undefined;
236 // Clone the incoming data, if any
237 data = jQuery.makeArray( data );
238 data.unshift( event );
241 event.currentTarget = elem;
243 // Trigger the event, it is assumed that "handle" is a function
244 var handle = jQuery.data( elem, "handle" );
246 handle.apply( elem, data );
249 // Handle triggering native .onfoo handlers (and on links since we don't call .click() for links)
250 if ( (!elem[ type ] || (jQuery.nodeName(elem, 'a') && type === "click")) && elem["on"+type] && elem["on"+type].apply( elem, data ) === false ) {
251 event.result = false;
254 // Trigger the native events (except for clicks on links)
255 if ( !bubbling && elem[ type ] && !event.isDefaultPrevented() && !(jQuery.nodeName(elem, 'a') && type === "click") ) {
256 this.triggered = true;
259 // prevent IE from throwing an error for some hidden elements
263 this.triggered = false;
265 if ( !event.isPropagationStopped() ) {
266 var parent = elem.parentNode || elem.ownerDocument;
268 jQuery.event.trigger( event, data, parent, true );
273 handle: function( event ) {
274 // returned undefined or false
277 event = arguments[0] = jQuery.event.fix( event || window.event );
278 event.currentTarget = this;
280 // Namespaced event handlers
281 var namespaces = event.type.split(".");
282 event.type = namespaces.shift();
284 // Cache this now, all = true means, any handler
285 all = !namespaces.length && !event.exclusive;
287 var namespace = new RegExp("(^|\\.)" + namespaces.slice().sort().join(".*\\.") + "(\\.|$)");
289 handlers = ( jQuery.data(this, "events") || {} )[ event.type ];
291 for ( var j in handlers ) {
292 var handler = handlers[ j ];
294 // Filter the functions by class
295 if ( all || namespace.test(handler.type) ) {
296 // Pass in a reference to the handler function itself
297 // So that we can later remove it
298 event.handler = handler;
299 event.data = handler.data;
301 var ret = handler.apply( this, arguments );
303 if ( ret !== undefined ) {
305 if ( ret === false ) {
306 event.preventDefault();
307 event.stopPropagation();
311 if ( event.isImmediatePropagationStopped() ) {
319 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(" "),
321 fix: function( event ) {
322 if ( event[ expando ] ) {
326 // store a copy of the original event object
327 // and "clone" to set read-only properties
328 var originalEvent = event;
329 event = jQuery.Event( originalEvent );
331 for ( var i = this.props.length, prop; i; ) {
332 prop = this.props[ --i ];
333 event[ prop ] = originalEvent[ prop ];
336 // Fix target property, if necessary
337 if ( !event.target ) {
338 event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either
341 // check if target is a textnode (safari)
342 if ( event.target.nodeType === 3 ) {
343 event.target = event.target.parentNode;
346 // Add relatedTarget, if necessary
347 if ( !event.relatedTarget && event.fromElement ) {
348 event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement;
351 // Calculate pageX/Y if missing and clientX/Y available
352 if ( event.pageX == null && event.clientX != null ) {
353 var doc = document.documentElement, body = document.body;
354 event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc.clientLeft || 0);
355 event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc.clientTop || 0);
358 // Add which for key events
359 if ( !event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode) ) {
360 event.which = event.charCode || event.keyCode;
363 // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
364 if ( !event.metaKey && event.ctrlKey ) {
365 event.metaKey = event.ctrlKey;
368 // Add which for click: 1 == left; 2 == middle; 3 == right
369 // Note: button is not normalized, so don't use it
370 if ( !event.which && event.button ) {
371 event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
377 proxy: function( fn, proxy ) {
378 proxy = proxy || function() { return fn.apply( this, arguments ); };
379 // Set the guid of unique handler to the same of original handler, so it can be removed
380 proxy.guid = fn.guid = fn.guid || proxy.guid || this.guid++;
381 // So proxy can be declared as an argument
387 // Make sure the ready event is setup
389 teardown: function() {}
393 add: function( proxy, data, namespaces ) {
394 jQuery.extend( proxy, data || {} );
395 proxy.guid += data.selector + data.live;
396 jQuery.event.add( this, data.live, liveHandler );
399 teardown: function( namespaces ) {
400 jQuery.event.remove( this, namespaces[0], liveHandler );
406 jQuery.Event = function( src ){
407 // Allow instantiation without the 'new' keyword
408 if ( !this.preventDefault ) {
409 return new jQuery.Event( src );
413 if ( src && src.type ) {
414 this.originalEvent = src;
415 this.type = src.type;
421 // timeStamp is buggy for some events on Firefox(#3843)
422 // So we won't rely on the native value
423 this.timeStamp = now();
426 this[ expando ] = true;
429 function returnFalse() {
432 function returnTrue() {
436 // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
437 // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
438 jQuery.Event.prototype = {
439 preventDefault: function() {
440 this.isDefaultPrevented = returnTrue;
442 var e = this.originalEvent;
446 // if preventDefault exists run it on the original event
447 if ( e.preventDefault ) {
450 // otherwise set the returnValue property of the original event to false (IE)
451 e.returnValue = false;
453 stopPropagation: function() {
454 this.isPropagationStopped = returnTrue;
456 var e = this.originalEvent;
460 // if stopPropagation exists run it on the original event
461 if ( e.stopPropagation ) {
464 // otherwise set the cancelBubble property of the original event to true (IE)
465 e.cancelBubble = true;
467 stopImmediatePropagation: function(){
468 this.isImmediatePropagationStopped = returnTrue;
469 this.stopPropagation();
471 isDefaultPrevented: returnFalse,
472 isPropagationStopped: returnFalse,
473 isImmediatePropagationStopped: returnFalse
475 // Checks if an event happened on an element within another element
476 // Used in jQuery.event.special.mouseenter and mouseleave handlers
477 var withinElement = function( event ) {
478 // Check if mouse(over|out) are still within the same parent element
479 var parent = event.relatedTarget;
480 // Traverse up the tree
481 while ( parent && parent != this ) {
482 try { parent = parent.parentNode; }
483 catch(e) { parent = this; }
486 if ( parent != this ) {
487 // set the correct event type
488 event.type = event.data;
489 // handle event if we actually just moused on to a non sub-element
490 jQuery.event.handle.apply( this, arguments );
495 mouseover: 'mouseenter',
496 mouseout: 'mouseleave'
497 }, function( orig, fix ) {
498 jQuery.event.special[ fix ] = {
500 jQuery.event.add( this, orig, withinElement, fix );
502 teardown: function(){
503 jQuery.event.remove( this, orig, withinElement );
509 bind: function( type, data, fn ) {
510 return type === "unload" ? this.one(type, data, fn) : this.each(function() {
511 jQuery.event.add( this, type, fn || data, fn && data );
515 one: function( type, data, fn ) {
516 var one = jQuery.event.proxy( fn || data, function( event ) {
517 jQuery( this ).unbind( event, one );
518 return (fn || data).apply( this, arguments );
520 return this.each(function() {
521 jQuery.event.add( this, type, one, fn && data );
525 unbind: function( type, fn ) {
526 return this.each(function() {
527 jQuery.event.remove( this, type, fn );
531 trigger: function( type, data ) {
532 return this.each(function() {
533 jQuery.event.trigger( type, data, this );
537 triggerHandler: function( type, data ) {
539 var event = jQuery.Event( type );
540 event.preventDefault();
541 event.stopPropagation();
542 jQuery.event.trigger( event, data, this[0] );
547 toggle: function( fn ) {
548 // Save reference to arguments for access in closure
549 var args = arguments, i = 1;
551 // link all the functions, so any of them can unbind this click handler
552 while( i < args.length ) {
553 jQuery.event.proxy( fn, args[ i++ ] );
556 return this.click( jQuery.event.proxy( fn, function( event ) {
557 // Figure out which function to execute
558 this.lastToggle = ( this.lastToggle || 0 ) % i;
560 // Make sure that clicks stop
561 event.preventDefault();
563 // and execute the function
564 return args[ this.lastToggle++ ].apply( this, arguments ) || false;
568 hover: function( fnOver, fnOut ) {
569 return this.mouseenter( fnOver ).mouseleave( fnOut );
572 ready: function( fn ) {
573 // Attach the listeners
576 // If the DOM is already ready
577 if ( jQuery.isReady ) {
578 // Execute the function immediately
579 fn.call( document, jQuery );
581 // Otherwise, remember the function for later
583 // Add the function to the wait list
584 jQuery.readyList.push( fn );
590 live: function( type, data, fn ) {
591 jQuery( this.context ).bind( liveConvert( type, this.selector ), {
592 data: fn && data, selector: this.selector, live: type
597 die: function( type, fn ) {
598 jQuery( this.context ).unbind( liveConvert( type, this.selector ), fn ? { guid: fn.guid + this.selector + type } : null );
603 function liveHandler( event ) {
604 var stop = true, elems = [], args = arguments;
606 jQuery.each( jQuery.data( this, "events" ).live || [], function( i, fn ) {
607 if ( fn.live === event.type ) {
608 var elem = jQuery( event.target ).closest( fn.selector )[0];
610 elems.push({ elem: elem, fn: fn });
615 elems.sort(function( a, b ) {
616 return jQuery.data( a.elem, "closest" ) - jQuery.data( b.elem, "closest" );
619 jQuery.each(elems, function() {
620 event.currentTarget = this.elem;
621 event.data = this.fn.data
622 if ( this.fn.apply( this.elem, args ) === false ) {
623 return (stop = false);
630 function liveConvert( type, selector ) {
631 return ["live", type, selector.replace(/\./g, "`").replace(/ /g, "|")].join(".");
637 // Handle when the DOM is ready
639 // Make sure that the DOM is not already loaded
640 if ( !jQuery.isReady ) {
641 // Remember that the DOM is ready
642 jQuery.isReady = true;
644 // If there are functions bound, to execute
645 if ( jQuery.readyList ) {
646 // Execute all of them
648 while ( (fn = jQuery.readyList[ i++ ]) ) {
649 fn.call( document, jQuery );
652 // Reset the list of functions
653 jQuery.readyList = null;
656 // Trigger any bound ready events
657 jQuery( document ).triggerHandler( "ready" );
662 var readyBound = false;
664 function bindReady() {
665 if ( readyBound ) return;
668 // Mozilla, Opera and webkit nightlies currently support this event
669 if ( document.addEventListener ) {
670 // Use the handy event callback
671 document.addEventListener( "DOMContentLoaded", function() {
672 document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
676 // If IE event model is used
677 } else if ( document.attachEvent ) {
678 // ensure firing before onload,
679 // maybe late but safe also for iframes
680 document.attachEvent("onreadystatechange", function() {
681 if ( document.readyState === "complete" ) {
682 document.detachEvent( "onreadystatechange", arguments.callee );
687 // If IE and not an iframe
688 // continually check to see if the document is ready
689 if ( document.documentElement.doScroll && window === window.top ) (function() {
690 if ( jQuery.isReady ) {
695 // If IE is used, use the trick by Diego Perini
696 // http://javascript.nwbox.com/IEContentLoaded/
697 document.documentElement.doScroll("left");
699 setTimeout( arguments.callee, 0 );
703 // and execute any waiting functions
708 // A fallback to window.onload, that will always work
709 jQuery.event.add( window, "load", jQuery.ready );
712 jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
713 "mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave," +
714 "change,select,submit,keydown,keypress,keyup,error").split(","), function( i, name ) {
716 // Handle event binding
717 jQuery.fn[ name ] = function( fn ) {
718 return fn ? this.bind (name, fn ) : this.trigger( name );
722 // Prevent memory leaks in IE
723 // And prevent errors on refresh with events like mouseover in other browsers
724 // Window isn't included so as not to unbind existing unload events
726 // - http://isaacschlueter.com/2006/10/msie-memory-leaks/
727 // - https://bugzilla.mozilla.org/show_bug.cgi?id=252542
728 jQuery( window ).bind( 'unload', function() {
729 for ( var id in jQuery.cache ) {
731 if ( id != 1 && jQuery.cache[ id ].handle ) {
732 jQuery.event.remove( jQuery.cache[ id ].handle.elem );