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 ( jQuery.browser.msie && elem.setInterval )
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 if ( typeof jQuery !== "undefined" && !jQuery.event.triggered )
44 return jQuery.event.handle.apply(arguments.callee.elem, arguments);
46 // Add elem as a property of the handle function
47 // This is to prevent a memory leak with non-native
51 // Handle multiple events separated by a space
52 // jQuery(...).bind("mouseover mouseout", fn);
53 jQuery.each(types.split(/\s+/), function(index, type) {
54 // Namespaced event handlers
55 var parts = type.split(".");
57 handler.type = parts.sort().join(".");
59 // Get the current list of functions bound to this event
60 var handlers = events[type];
62 // Init the event handler queue
64 handlers = events[type] = {};
66 // Check for a special event handler
67 // Only use addEventListener/attachEvent if the special
68 // events handler returns false
69 if ( !jQuery.event.special[type] || jQuery.event.special[type].setup.call(elem,data) === false ) {
70 // Bind the global event handler to the element
71 if (elem.addEventListener)
72 elem.addEventListener(type, handle, false);
73 else if (elem.attachEvent)
74 elem.attachEvent("on" + type, handle);
78 // Add the function to the element's handler list
79 handlers[handler.guid] = handler;
81 // Keep track of which events have been used, for global triggering
82 jQuery.event.global[type] = true;
85 // Nullify elem to prevent memory leaks in IE
92 // Detach an event or set of events from an element
93 remove: function(elem, types, handler) {
94 // don't do events on text and comment nodes
95 if ( elem.nodeType == 3 || elem.nodeType == 8 )
98 var events = jQuery.data(elem, "events"), ret, index;
101 // Unbind all events for the element
102 if ( types === undefined || (typeof types === "string" && types.charAt(0) == ".") )
103 for ( var type in events )
104 this.remove( elem, type + (types || "") );
106 // types is actually an event object here
108 handler = types.handler;
112 // Handle multiple events seperated by a space
113 // jQuery(...).unbind("mouseover mouseout", fn);
114 jQuery.each(types.split(/\s+/), function(index, type){
115 // Namespaced event handlers
116 var namespace = type.split(".");
117 type = namespace.shift();
118 namespace = RegExp(namespace.sort().join(".*\\.") + "(\\.|$)");
120 if ( events[type] ) {
121 // remove the given handler for the given type
123 delete events[type][handler.guid];
125 // remove all handlers for the given type
127 for ( handler in events[type] )
128 // Handle the removal of namespaced events
129 if ( namespace.test(events[type][handler].type) )
130 delete events[type][handler];
132 // remove generic event handler if no more handlers exist
133 for ( ret in events[type] ) break;
135 if ( !jQuery.event.special[type] || jQuery.event.special[type].teardown.call(elem) === false ) {
136 if (elem.removeEventListener)
137 elem.removeEventListener(type, jQuery.data(elem, "handle"), false);
138 else if (elem.detachEvent)
139 elem.detachEvent("on" + type, jQuery.data(elem, "handle"));
148 // Remove the expando if it's no longer used
149 for ( ret in events ) break;
151 var handle = jQuery.data( elem, "handle" );
152 if ( handle ) handle.elem = null;
153 jQuery.removeData( elem, "events" );
154 jQuery.removeData( elem, "handle" );
159 trigger: function(type, data, elem, donative, extra) {
160 // Clone the incoming data, if any
161 data = jQuery.makeArray(data);
163 if ( type.indexOf("!") >= 0 ) {
164 type = type.slice(0, -1);
165 var exclusive = true;
168 // Handle a global trigger
170 // Only trigger if we've ever bound an event for it
171 if ( this.global[type] )
172 jQuery.each( jQuery.cache, function(){
173 if ( this.events && this.events[type] )
174 jQuery.event.trigger( type, data, this.handle.elem );
177 // Handle triggering a single element
179 // don't do events on text and comment nodes
180 if ( elem.nodeType == 3 || elem.nodeType == 8 )
183 var val, ret, fn = jQuery.isFunction( elem[ type ] || null ),
184 // Check to see if we need to provide a fake event, or not
185 event = !data[0] || !data[0].preventDefault;
187 // Pass along a fake event
192 preventDefault: function(){},
193 stopPropagation: function(){},
194 stopImmediatePropagation:stopImmediatePropagation,
197 data[0][expando] = true; // no need to fix fake event
200 // Enforce the right trigger type
203 data[0].exclusive = true;
205 // Trigger the event, it is assumed that "handle" is a function
206 var handle = jQuery.data(elem, "handle");
208 val = handle.apply( elem, data );
210 // Handle triggering native .onfoo handlers (and on links since we don't call .click() for links)
211 if ( (!fn || (jQuery.nodeName(elem, 'a') && type == "click")) && elem["on"+type] && elem["on"+type].apply( elem, data ) === false )
214 // Extra functions don't get the custom event object
218 // Handle triggering of extra function
219 if ( extra && jQuery.isFunction( extra ) ) {
220 // call the extra function and tack the current return value on the end for possible inspection
221 ret = extra.apply( elem, val == null ? data : data.concat( val ) );
222 // if anything is returned, give it precedence and have it overwrite the previous value
223 if ( ret !== undefined )
227 // Trigger the native events (except for clicks on links)
228 if ( fn && donative !== false && val !== false && !(jQuery.nodeName(elem, 'a') && type == "click") ) {
229 this.triggered = true;
232 // prevent IE from throwing an error for some hidden elements
236 this.triggered = false;
242 handle: function(event) {
243 // returned undefined or false
244 var val, ret, namespace, all, handlers;
246 event = arguments[0] = jQuery.event.fix( event || window.event );
248 // Namespaced event handlers
249 namespace = event.type.split(".");
250 event.type = namespace.shift();
251 namespace = RegExp(namespace.sort().join(".*\\.") + "(\\.|$)");
252 // Cache this now, all = true means, any handler
253 all = !namespace && !event.exclusive;
255 handlers = ( jQuery.data(this, "events") || {} )[event.type];
257 for ( var j in handlers ) {
258 var handler = handlers[j];
260 // Filter the functions by class
261 if ( all || namespace.test(handler.type) ) {
262 // Pass in a reference to the handler function itself
263 // So that we can later remove it
264 event.handler = handler;
265 event.data = handler.data;
267 ret = handler.apply( this, arguments );
272 if ( ret === false ) {
273 event.preventDefault();
274 event.stopPropagation();
286 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(" "),
288 fix: function(event) {
289 if ( event[expando] )
292 // store a copy of the original event object
293 // and "clone" to set read-only properties
294 var originalEvent = event;
295 event = { originalEvent: originalEvent };
297 for ( var i = this.props.length, prop; i; ){
298 prop = this.props[ --i ];
299 event[ prop ] = originalEvent[ prop ];
303 event[expando] = true;
305 // add preventDefault and stopPropagation since
306 // they will not work on the clone
307 event.preventDefault = function() {
308 // if preventDefault exists run it on the original event
309 if (originalEvent.preventDefault)
310 originalEvent.preventDefault();
311 // otherwise set the returnValue property of the original event to false (IE)
312 originalEvent.returnValue = false;
314 event.stopPropagation = function() {
315 // if stopPropagation exists run it on the original event
316 if (originalEvent.stopPropagation)
317 originalEvent.stopPropagation();
318 // otherwise set the cancelBubble property of the original event to true (IE)
319 originalEvent.cancelBubble = true;
322 event.stopImmediatePropagation = stopImmediatePropagation;
325 event.timeStamp = event.timeStamp || now();
327 // Fix target property, if necessary
329 event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either
331 // check if target is a textnode (safari)
332 if ( event.target.nodeType == 3 )
333 event.target = event.target.parentNode;
335 // Add relatedTarget, if necessary
336 if ( !event.relatedTarget && event.fromElement )
337 event.relatedTarget = event.fromElement == event.target ? event.toElement : event.fromElement;
339 // Calculate pageX/Y if missing and clientX/Y available
340 if ( event.pageX == null && event.clientX != null ) {
341 var doc = document.documentElement, body = document.body;
342 event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc.clientLeft || 0);
343 event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc.clientTop || 0);
346 // Add which for key events
347 if ( !event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode) )
348 event.which = event.charCode || event.keyCode;
350 // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
351 if ( !event.metaKey && event.ctrlKey )
352 event.metaKey = event.ctrlKey;
354 // Add which for click: 1 == left; 2 == middle; 3 == right
355 // Note: button is not normalized, so don't use it
356 if ( !event.which && event.button )
357 event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
362 proxy: function( fn, proxy ){
363 // Set the guid of unique handler to the same of original handler, so it can be removed
364 proxy.guid = fn.guid = fn.guid || proxy.guid || this.guid++;
365 // So proxy can be declared as an argument
371 // Make sure the ready event is setup
373 teardown: function() {}
378 function stopImmediatePropagation(){
380 this.stopPropagation();
383 if ( !jQuery.browser.msie ){
384 // Checks if an event happened on an element within another element
385 // Used in jQuery.event.special.mouseenter and mouseleave handlers
386 var withinElement = function(event) {
387 // Check if mouse(over|out) are still within the same parent element
388 var parent = event.relatedTarget;
389 // Traverse up the tree
390 while ( parent && parent != this )
391 try { parent = parent.parentNode; }
392 catch(e) { parent = this; }
394 if( parent != this ){
395 // set the correct event type
396 event.type = event.data;
397 // handle event if we actually just moused on to a non sub-element
398 jQuery.event.handle.apply( this, arguments );
403 mouseover: 'mouseenter',
404 mouseout: 'mouseleave'
405 }, function( orig, fix ){
406 jQuery.event.special[ fix ] = {
408 jQuery.event.add( this, orig, withinElement, fix );
410 teardown: function(){
411 jQuery.event.remove( this, orig, withinElement );
418 bind: function( type, data, fn ) {
419 return type == "unload" ? this.one(type, data, fn) : this.each(function(){
420 jQuery.event.add( this, type, fn || data, fn && data );
424 one: function( type, data, fn ) {
425 var one = jQuery.event.proxy( fn || data, function(event) {
426 jQuery(this).unbind(event, one);
427 return (fn || data).apply( this, arguments );
429 return this.each(function(){
430 jQuery.event.add( this, type, one, fn && data);
434 unbind: function( type, fn ) {
435 return this.each(function(){
436 jQuery.event.remove( this, type, fn );
440 trigger: function( type, data, fn ) {
441 return this.each(function(){
442 jQuery.event.trigger( type, data, this, true, fn );
446 triggerHandler: function( type, data, fn ) {
447 return this[0] && jQuery.event.trigger( type, data, this[0], false, fn );
450 toggle: function( fn ) {
451 // Save reference to arguments for access in closure
452 var args = arguments, i = 1;
454 // link all the functions, so any of them can unbind this click handler
455 while( i < args.length )
456 jQuery.event.proxy( fn, args[i++] );
458 return this.click( jQuery.event.proxy( fn, function(event) {
459 // Figure out which function to execute
460 this.lastToggle = ( this.lastToggle || 0 ) % i;
462 // Make sure that clicks stop
463 event.preventDefault();
465 // and execute the function
466 return args[ this.lastToggle++ ].apply( this, arguments ) || false;
470 hover: function(fnOver, fnOut) {
471 return this.mouseenter(fnOver).mouseleave(fnOut);
474 ready: function(fn) {
475 // Attach the listeners
478 // If the DOM is already ready
479 if ( jQuery.isReady )
480 // Execute the function immediately
481 fn.call( document, jQuery );
483 // Otherwise, remember the function for later
485 // Add the function to the wait list
486 jQuery.readyList.push( function() { return fn.call(this, jQuery); } );
495 // Handle when the DOM is ready
497 // Make sure that the DOM is not already loaded
498 if ( !jQuery.isReady ) {
499 // Remember that the DOM is ready
500 jQuery.isReady = true;
502 // If there are functions bound, to execute
503 if ( jQuery.readyList ) {
504 // Execute all of them
505 jQuery.each( jQuery.readyList, function(){
506 this.call( document );
509 // Reset the list of functions
510 jQuery.readyList = null;
513 // Trigger any bound ready events
514 jQuery(document).triggerHandler("ready");
519 var readyBound = false;
521 function bindReady(){
522 if ( readyBound ) return;
525 // Mozilla, Opera and webkit nightlies currently support this event
526 if ( document.addEventListener ) {
527 // Use the handy event callback
528 document.addEventListener( "DOMContentLoaded", function(){
529 document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
533 // If IE event model is used
534 } else if ( document.attachEvent ) {
535 // ensure firing before onload,
536 // maybe late but safe also for iframes
537 document.attachEvent("onreadystatechange", function(){
538 if ( document.readyState === "complete" ) {
539 document.detachEvent( "onreadystatechange", arguments.callee );
544 // If IE and not an iframe
545 // continually check to see if the document is ready
546 if ( document.documentElement.doScroll && !window.frameElement ) (function(){
547 if ( jQuery.isReady ) return;
550 // If IE is used, use the trick by Diego Perini
551 // http://javascript.nwbox.com/IEContentLoaded/
552 document.documentElement.doScroll("left");
554 setTimeout( arguments.callee, 0 );
558 // and execute any waiting functions
563 // A fallback to window.onload, that will always work
564 jQuery.event.add( window, "load", jQuery.ready );
567 jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
568 "mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave," +
569 "change,select,submit,keydown,keypress,keyup,error").split(","), function(i, name){
571 // Handle event binding
572 jQuery.fn[name] = function(fn){
573 return fn ? this.bind(name, fn) : this.trigger(name);
577 // Prevent memory leaks in IE
578 // And prevent errors on refresh with events like mouseover in other browsers
579 // Window isn't included so as not to unbind existing unload events
580 jQuery( window ).bind( 'unload', function(){
581 for ( var id in jQuery.cache )
583 if ( id != 1 && jQuery.cache[ id ].handle )
584 jQuery.event.remove( jQuery.cache[ id ].handle.elem );