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;
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 jQuery.each( jQuery.cache, function() {
218 if ( this.events && this.events[type] ) {
219 jQuery.event.trigger( event, data, this.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 && doc.clientLeft || body && body.clientLeft || 0);
355 event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.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 // Firefox sometimes assigns relatedTarget a XUL element
483 // which we cannot access the parentNode property of
484 try { parent = parent.parentNode; }
485 // assuming we've left the element since we most likely mousedover a xul element
489 if ( parent != this ) {
490 // set the correct event type
491 event.type = event.data;
492 // handle event if we actually just moused on to a non sub-element
493 jQuery.event.handle.apply( this, arguments );
498 mouseover: 'mouseenter',
499 mouseout: 'mouseleave'
500 }, function( orig, fix ) {
501 jQuery.event.special[ fix ] = {
503 jQuery.event.add( this, orig, withinElement, fix );
505 teardown: function(){
506 jQuery.event.remove( this, orig, withinElement );
512 bind: function( type, data, fn ) {
513 return type === "unload" ? this.one(type, data, fn) : this.each(function() {
514 jQuery.event.add( this, type, fn || data, fn && data );
518 one: function( type, data, fn ) {
519 var one = jQuery.event.proxy( fn || data, function( event ) {
520 jQuery( this ).unbind( event, one );
521 return (fn || data).apply( this, arguments );
523 return this.each(function() {
524 jQuery.event.add( this, type, one, fn && data );
528 unbind: function( type, fn ) {
529 return this.each(function() {
530 jQuery.event.remove( this, type, fn );
534 trigger: function( type, data ) {
535 return this.each(function() {
536 jQuery.event.trigger( type, data, this );
540 triggerHandler: function( type, data ) {
542 var event = jQuery.Event( type );
543 event.preventDefault();
544 event.stopPropagation();
545 jQuery.event.trigger( event, data, this[0] );
550 toggle: function( fn ) {
551 // Save reference to arguments for access in closure
552 var args = arguments, i = 1;
554 // link all the functions, so any of them can unbind this click handler
555 while( i < args.length ) {
556 jQuery.event.proxy( fn, args[ i++ ] );
559 return this.click( jQuery.event.proxy( fn, function( event ) {
560 // Figure out which function to execute
561 this.lastToggle = ( this.lastToggle || 0 ) % i;
563 // Make sure that clicks stop
564 event.preventDefault();
566 // and execute the function
567 return args[ this.lastToggle++ ].apply( this, arguments ) || false;
571 hover: function( fnOver, fnOut ) {
572 return this.mouseenter( fnOver ).mouseleave( fnOut );
575 ready: function( fn ) {
576 // Attach the listeners
579 // If the DOM is already ready
580 if ( jQuery.isReady ) {
581 // Execute the function immediately
582 fn.call( document, jQuery );
584 // Otherwise, remember the function for later
586 // Add the function to the wait list
587 jQuery.readyList.push( fn );
593 live: function( type, data, fn ) {
594 jQuery( this.context ).bind( liveConvert( type, this.selector ), {
595 data: fn && data, selector: this.selector, live: type
600 die: function( type, fn ) {
601 jQuery( this.context ).unbind( liveConvert( type, this.selector ), fn ? { guid: fn.guid + this.selector + type } : null );
606 function liveHandler( event ) {
607 var stop = true, elems = [], args = arguments;
609 jQuery.each( jQuery.data( this, "events" ).live || [], function( i, fn ) {
610 if ( fn.live === event.type ) {
611 var elem = jQuery( event.target ).closest( fn.selector )[0];
613 elems.push({ elem: elem, fn: fn });
618 elems.sort(function( a, b ) {
619 return jQuery.data( a.elem, "closest" ) - jQuery.data( b.elem, "closest" );
622 jQuery.each(elems, function() {
623 event.currentTarget = this.elem;
624 event.data = this.fn.data
625 if ( this.fn.apply( this.elem, args ) === false ) {
626 return (stop = false);
633 function liveConvert( type, selector ) {
634 return ["live", type, selector.replace(/\./g, "`").replace(/ /g, "|")].join(".");
640 // Handle when the DOM is ready
642 // Make sure that the DOM is not already loaded
643 if ( !jQuery.isReady ) {
644 // Remember that the DOM is ready
645 jQuery.isReady = true;
647 // If there are functions bound, to execute
648 if ( jQuery.readyList ) {
649 // Execute all of them
651 while ( (fn = jQuery.readyList[ i++ ]) ) {
652 fn.call( document, jQuery );
655 // Reset the list of functions
656 jQuery.readyList = null;
659 // Trigger any bound ready events
660 jQuery( document ).triggerHandler( "ready" );
665 var readyBound = false;
667 function bindReady() {
668 if ( readyBound ) return;
671 // Mozilla, Opera and webkit nightlies currently support this event
672 if ( document.addEventListener ) {
673 // Use the handy event callback
674 document.addEventListener( "DOMContentLoaded", function() {
675 document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
679 // If IE event model is used
680 } else if ( document.attachEvent ) {
681 // ensure firing before onload,
682 // maybe late but safe also for iframes
683 document.attachEvent("onreadystatechange", function() {
684 if ( document.readyState === "complete" ) {
685 document.detachEvent( "onreadystatechange", arguments.callee );
690 // If IE and not an iframe
691 // continually check to see if the document is ready
692 if ( document.documentElement.doScroll && window === window.top ) (function() {
693 if ( jQuery.isReady ) {
698 // If IE is used, use the trick by Diego Perini
699 // http://javascript.nwbox.com/IEContentLoaded/
700 document.documentElement.doScroll("left");
702 setTimeout( arguments.callee, 0 );
706 // and execute any waiting functions
711 // A fallback to window.onload, that will always work
712 jQuery.event.add( window, "load", jQuery.ready );
715 jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
716 "mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave," +
717 "change,select,submit,keydown,keypress,keyup,error").split(","), function( i, name ) {
719 // Handle event binding
720 jQuery.fn[ name ] = function( fn ) {
721 return fn ? this.bind (name, fn ) : this.trigger( name );
725 // Prevent memory leaks in IE
726 // And prevent errors on refresh with events like mouseover in other browsers
727 // Window isn't included so as not to unbind existing unload events
729 // - http://isaacschlueter.com/2006/10/msie-memory-leaks/
730 // - https://bugzilla.mozilla.org/show_bug.cgi?id=252542
731 jQuery( window ).bind( 'unload', function() {
732 for ( var id in jQuery.cache ) {
734 if ( id != 1 && jQuery.cache[ id ].handle ) {
735 jQuery.event.remove( jQuery.cache[ id ].handle.elem );