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 )
14 // For whatever reason, IE has trouble passing the window object
15 // around, causing it to be cloned in the process
16 if ( elem.setInterval && elem != window )
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 = this.proxy( fn, function() {
30 // Pass arguments and context to original handler
31 return fn.apply(this, arguments);
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 jQuery.each(types.split(/\s+/), function(index, type) {
55 // Namespaced event handlers
56 var parts = type.split(".");
58 handler.type = parts.sort().join(".");
60 // Get the current list of functions bound to this event
61 var handlers = events[type];
63 // Init the event handler queue
65 handlers = events[type] = {};
67 // Check for a special event handler
68 // Only use addEventListener/attachEvent if the special
69 // events handler returns false
70 if ( !jQuery.event.special[type] || jQuery.event.special[type].setup.call(elem,data) === false ) {
71 // Bind the global event handler to the element
72 if (elem.addEventListener)
73 elem.addEventListener(type, handle, false);
74 else if (elem.attachEvent)
75 elem.attachEvent("on" + type, handle);
79 // Add the function to the element's handler list
80 handlers[handler.guid] = handler;
82 // Keep track of which events have been used, for global triggering
83 jQuery.event.global[type] = true;
86 // Nullify elem to prevent memory leaks in IE
93 // Detach an event or set of events from an element
94 remove: function(elem, types, handler) {
95 // don't do events on text and comment nodes
96 if ( elem.nodeType == 3 || elem.nodeType == 8 )
99 var events = jQuery.data(elem, "events"), ret, index;
102 // Unbind all events for the element
103 if ( types === undefined || (typeof types === "string" && types.charAt(0) == ".") )
104 for ( var type in events )
105 this.remove( elem, type + (types || "") );
107 // types is actually an event object here
109 handler = types.handler;
113 // Handle multiple events seperated by a space
114 // jQuery(...).unbind("mouseover mouseout", fn);
115 jQuery.each(types.split(/\s+/), function(index, type){
116 // Namespaced event handlers
117 var namespace = type.split(".");
118 type = namespace.shift();
119 namespace = RegExp("(^|\\.)" + namespace.sort().join(".*\\.") + "(\\.|$)");
121 if ( events[type] ) {
122 // remove the given handler for the given type
124 delete events[type][handler.guid];
126 // remove all handlers for the given type
128 for ( handler in events[type] )
129 // Handle the removal of namespaced events
130 if ( namespace.test(events[type][handler].type) )
131 delete events[type][handler];
133 // remove generic event handler if no more handlers exist
134 for ( ret in events[type] ) break;
136 if ( !jQuery.event.special[type] || jQuery.event.special[type].teardown.call(elem) === false ) {
137 if (elem.removeEventListener)
138 elem.removeEventListener(type, jQuery.data(elem, "handle"), false);
139 else if (elem.detachEvent)
140 elem.detachEvent("on" + type, jQuery.data(elem, "handle"));
149 // Remove the expando if it's no longer used
150 for ( ret in events ) break;
152 var handle = jQuery.data( elem, "handle" );
153 if ( handle ) handle.elem = null;
154 jQuery.removeData( elem, "events" );
155 jQuery.removeData( elem, "handle" );
160 trigger: function(type, data, elem, donative, extra) {
161 // Clone the incoming data, if any
162 data = jQuery.makeArray(data);
164 if ( type.indexOf("!") >= 0 ) {
165 type = type.slice(0, -1);
166 var exclusive = true;
169 // Handle a global trigger
171 // Only trigger if we've ever bound an event for it
172 if ( this.global[type] )
173 jQuery.each( jQuery.cache, function(){
174 if ( this.events && this.events[type] )
175 jQuery.event.trigger( type, data, this.handle.elem );
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
193 preventDefault: function(){},
194 stopPropagation: function(){},
195 stopImmediatePropagation:stopImmediatePropagation,
198 data[0][expando] = true; // no need to fix fake event
201 // Enforce the right trigger type
204 data[0].exclusive = true;
206 // Trigger the event, it is assumed that "handle" is a function
207 var handle = jQuery.data(elem, "handle");
209 val = handle.apply( elem, data );
211 // Handle triggering native .onfoo handlers (and on links since we don't call .click() for links)
212 if ( (!fn || (jQuery.nodeName(elem, 'a') && type == "click")) && elem["on"+type] && elem["on"+type].apply( elem, data ) === false )
215 if ( donative !== false && val !== false ) {
216 var parent = elem.parentNode || elem.ownerDocument;
218 jQuery.event.trigger(type, data, parent, donative);
221 // Extra functions don't get the custom event object
225 // Handle triggering of extra function
226 if ( extra && jQuery.isFunction( extra ) ) {
227 // call the extra function and tack the current return value on the end for possible inspection
228 ret = extra.apply( elem, val == null ? data : data.concat( val ) );
229 // if anything is returned, give it precedence and have it overwrite the previous value
230 if ( ret !== undefined )
234 // Trigger the native events (except for clicks on links)
235 if ( fn && donative !== false && val !== false && !(jQuery.nodeName(elem, 'a') && type == "click") ) {
236 this.triggered = true;
239 // prevent IE from throwing an error for some hidden elements
243 this.triggered = false;
249 handle: function(event) {
250 // returned undefined or false
251 var val, ret, namespace, all, handlers;
253 event = arguments[0] = jQuery.event.fix( event || window.event );
255 // Namespaced event handlers
256 namespace = event.type.split(".");
257 event.type = namespace.shift();
259 // Cache this now, all = true means, any handler
260 all = !namespace.length && !event.exclusive;
262 namespace = RegExp("(^|\\.)" + namespace.sort().join(".*\\.") + "(\\.|$)");
264 handlers = ( jQuery.data(this, "events") || {} )[event.type];
266 for ( var j in handlers ) {
267 var handler = handlers[j];
269 // Filter the functions by class
270 if ( all || namespace.test(handler.type) ) {
271 // Pass in a reference to the handler function itself
272 // So that we can later remove it
273 event.handler = handler;
274 event.data = handler.data;
276 ret = handler.apply( this, arguments );
281 if ( ret === false ) {
282 event.preventDefault();
283 event.stopPropagation();
295 props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target timeStamp toElement type view wheelDelta which".split(" "),
297 fix: function(event) {
298 if ( event[expando] )
301 // store a copy of the original event object
302 // and "clone" to set read-only properties
303 var originalEvent = event;
304 event = { originalEvent: originalEvent };
306 for ( var i = this.props.length, prop; i; ){
307 prop = this.props[ --i ];
308 event[ prop ] = originalEvent[ prop ];
312 event[expando] = true;
314 // add preventDefault and stopPropagation since
315 // they will not work on the clone
316 event.preventDefault = function() {
317 // if preventDefault exists run it on the original event
318 if (originalEvent.preventDefault)
319 originalEvent.preventDefault();
320 // otherwise set the returnValue property of the original event to false (IE)
321 originalEvent.returnValue = false;
323 event.stopPropagation = function() {
324 // if stopPropagation exists run it on the original event
325 if (originalEvent.stopPropagation)
326 originalEvent.stopPropagation();
327 // otherwise set the cancelBubble property of the original event to true (IE)
328 originalEvent.cancelBubble = true;
331 event.stopImmediatePropagation = stopImmediatePropagation;
334 event.timeStamp = event.timeStamp || now();
336 // Fix target property, if necessary
338 event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either
340 // check if target is a textnode (safari)
341 if ( event.target.nodeType == 3 )
342 event.target = event.target.parentNode;
344 // Add relatedTarget, if necessary
345 if ( !event.relatedTarget && event.fromElement )
346 event.relatedTarget = event.fromElement == event.target ? event.toElement : event.fromElement;
348 // Calculate pageX/Y if missing and clientX/Y available
349 if ( event.pageX == null && event.clientX != null ) {
350 var doc = document.documentElement, body = document.body;
351 event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc.clientLeft || 0);
352 event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc.clientTop || 0);
355 // Add which for key events
356 if ( !event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode) )
357 event.which = event.charCode || event.keyCode;
359 // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
360 if ( !event.metaKey && event.ctrlKey )
361 event.metaKey = event.ctrlKey;
363 // Add which for click: 1 == left; 2 == middle; 3 == right
364 // Note: button is not normalized, so don't use it
365 if ( !event.which && event.button )
366 event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
371 proxy: function( fn, proxy ){
372 // Set the guid of unique handler to the same of original handler, so it can be removed
373 proxy.guid = fn.guid = fn.guid || proxy.guid || this.guid++;
374 // So proxy can be declared as an argument
380 // Make sure the ready event is setup
382 teardown: function() {}
387 function stopImmediatePropagation(){
389 this.stopPropagation();
392 // Checks if an event happened on an element within another element
393 // Used in jQuery.event.special.mouseenter and mouseleave handlers
394 var withinElement = function(event) {
395 // Check if mouse(over|out) are still within the same parent element
396 var parent = event.relatedTarget;
397 // Traverse up the tree
398 while ( parent && parent != this )
399 try { parent = parent.parentNode; }
400 catch(e) { parent = this; }
402 if( parent != this ){
403 // set the correct event type
404 event.type = event.data;
405 // handle event if we actually just moused on to a non sub-element
406 jQuery.event.handle.apply( this, arguments );
411 mouseover: 'mouseenter',
412 mouseout: 'mouseleave'
413 }, function( orig, fix ){
414 jQuery.event.special[ fix ] = {
416 jQuery.event.add( this, orig, withinElement, fix );
418 teardown: function(){
419 jQuery.event.remove( this, orig, withinElement );
425 bind: function( type, data, fn ) {
426 return type == "unload" ? this.one(type, data, fn) : this.each(function(){
427 jQuery.event.add( this, type, fn || data, fn && data );
431 one: function( type, data, fn ) {
432 var one = jQuery.event.proxy( fn || data, function(event) {
433 jQuery(this).unbind(event, one);
434 return (fn || data).apply( this, arguments );
436 return this.each(function(){
437 jQuery.event.add( this, type, one, fn && data);
441 unbind: function( type, fn ) {
442 return this.each(function(){
443 jQuery.event.remove( this, type, fn );
447 trigger: function( type, data, fn ) {
448 return this.each(function(){
449 jQuery.event.trigger( type, data, this, true, fn );
453 triggerHandler: function( type, data, fn ) {
454 return this[0] && jQuery.event.trigger( type, data, this[0], false, fn );
457 toggle: function( fn ) {
458 // Save reference to arguments for access in closure
459 var args = arguments, i = 1;
461 // link all the functions, so any of them can unbind this click handler
462 while( i < args.length )
463 jQuery.event.proxy( fn, args[i++] );
465 return this.click( jQuery.event.proxy( fn, function(event) {
466 // Figure out which function to execute
467 this.lastToggle = ( this.lastToggle || 0 ) % i;
469 // Make sure that clicks stop
470 event.preventDefault();
472 // and execute the function
473 return args[ this.lastToggle++ ].apply( this, arguments ) || false;
477 hover: function(fnOver, fnOut) {
478 return this.mouseenter(fnOver).mouseleave(fnOut);
481 ready: function(fn) {
482 // Attach the listeners
485 // If the DOM is already ready
486 if ( jQuery.isReady )
487 // Execute the function immediately
488 fn.call( document, jQuery );
490 // Otherwise, remember the function for later
492 // Add the function to the wait list
493 jQuery.readyList.push( function() { return fn.call(this, jQuery); } );
502 // Handle when the DOM is ready
504 // Make sure that the DOM is not already loaded
505 if ( !jQuery.isReady ) {
506 // Remember that the DOM is ready
507 jQuery.isReady = true;
509 // If there are functions bound, to execute
510 if ( jQuery.readyList ) {
511 // Execute all of them
512 jQuery.each( jQuery.readyList, function(){
513 this.call( document );
516 // Reset the list of functions
517 jQuery.readyList = null;
520 // Trigger any bound ready events
521 jQuery(document).triggerHandler("ready");
526 var readyBound = false;
528 function bindReady(){
529 if ( readyBound ) return;
532 // Mozilla, Opera and webkit nightlies currently support this event
533 if ( document.addEventListener ) {
534 // Use the handy event callback
535 document.addEventListener( "DOMContentLoaded", function(){
536 document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
540 // If IE event model is used
541 } else if ( document.attachEvent ) {
542 // ensure firing before onload,
543 // maybe late but safe also for iframes
544 document.attachEvent("onreadystatechange", function(){
545 if ( document.readyState === "complete" ) {
546 document.detachEvent( "onreadystatechange", arguments.callee );
551 // If IE and not an iframe
552 // continually check to see if the document is ready
553 if ( document.documentElement.doScroll && !window.frameElement ) (function(){
554 if ( jQuery.isReady ) return;
557 // If IE is used, use the trick by Diego Perini
558 // http://javascript.nwbox.com/IEContentLoaded/
559 document.documentElement.doScroll("left");
561 setTimeout( arguments.callee, 0 );
565 // and execute any waiting functions
570 // A fallback to window.onload, that will always work
571 jQuery.event.add( window, "load", jQuery.ready );
574 jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
575 "mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave," +
576 "change,select,submit,keydown,keypress,keyup,error").split(","), function(i, name){
578 // Handle event binding
579 jQuery.fn[name] = function(fn){
580 return fn ? this.bind(name, fn) : this.trigger(name);
584 // Prevent memory leaks in IE
585 // And prevent errors on refresh with events like mouseover in other browsers
586 // Window isn't included so as not to unbind existing unload events
587 jQuery( window ).bind( 'unload', function(){
588 for ( var id in jQuery.cache )
590 if ( id != 1 && jQuery.cache[ id ].handle )
591 jQuery.event.remove( jQuery.cache[ id ].handle.elem );