2 * A number of helper functions used for managing events.
3 * Many of the ideas behind this code orignated 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 != undefined )
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 = function() {
30 // Pass arguments and context to original handler
31 return fn.apply(this, arguments);
34 // Store data in unique handler
37 // Set the guid of unique handler to the same of original handler, so it can be removed
38 handler.guid = fn.guid;
41 // Init the element's event structure
42 var events = jQuery.data(elem, "events") || jQuery.data(elem, "events", {}),
43 handle = jQuery.data(elem, "handle") || jQuery.data(elem, "handle", function(){
44 // returned undefined or false
47 // Handle the second event of a trigger and when
48 // an event is called after a page has unloaded
49 if ( typeof jQuery == "undefined" || jQuery.event.triggered )
52 val = jQuery.event.handle.apply(elem, arguments);
57 // Handle multiple events seperated by a space
58 // jQuery(...).bind("mouseover mouseout", fn);
59 jQuery.each(types.split(/\s+/), function(index, type) {
60 // Namespaced event handlers
61 var parts = type.split(".");
63 handler.type = parts[1];
65 // Get the current list of functions bound to this event
66 var handlers = events[type];
68 // Init the event handler queue
70 handlers = events[type] = {};
72 // Check for a special event handler
73 // Only use addEventListener/attachEvent if the special
74 // events handler returns false
75 if ( !jQuery.event.special[type] || jQuery.event.special[type].setup.call(elem) === false ) {
76 // Bind the global event handler to the element
77 if (elem.addEventListener)
78 elem.addEventListener(type, handle, false);
79 else if (elem.attachEvent)
80 elem.attachEvent("on" + type, handle);
84 // Add the function to the element's handler list
85 handlers[handler.guid] = handler;
87 // Keep track of which events have been used, for global triggering
88 jQuery.event.global[type] = true;
95 // Detach an event or set of events from an element
96 remove: function(elem, types, handler) {
97 // don't do events on text and comment nodes
98 if ( elem.nodeType == 3 || elem.nodeType == 8 )
101 var events = jQuery.data(elem, "events"), ret, index;
104 // Unbind all events for the element
106 for ( var type in events )
107 this.remove( elem, type );
109 // types is actually an event object here
111 handler = types.handler;
115 // Handle multiple events seperated by a space
116 // jQuery(...).unbind("mouseover mouseout", fn);
117 jQuery.each(types.split(/\s+/), function(index, type){
118 // Namespaced event handlers
119 var parts = type.split(".");
122 if ( events[type] ) {
123 // remove the given handler for the given type
125 delete events[type][handler.guid];
127 // remove all handlers for the given type
129 for ( handler in events[type] )
130 // Handle the removal of namespaced events
131 if ( !parts[1] || events[type][handler].type == parts[1] )
132 delete events[type][handler];
134 // remove generic event handler if no more handlers exist
135 for ( ret in events[type] ) break;
137 if ( !jQuery.event.special[type] || jQuery.event.special[type].teardown.call(this, elem) === false ) {
138 if (elem.removeEventListener)
139 elem.removeEventListener(type, jQuery.data(elem, "handle"), false);
140 else if (elem.detachEvent)
141 elem.detachEvent("on" + type, jQuery.data(elem, "handle"));
150 // Remove the expando if it's no longer used
151 for ( ret in events ) break;
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 // Handle a global trigger
165 // Only trigger if we've ever bound an event for it
166 if ( this.global[type] )
167 jQuery("*").add([window, document]).trigger(type, data);
169 // Handle triggering a single element
171 // don't do events on text and comment nodes
172 if ( elem.nodeType == 3 || elem.nodeType == 8 )
175 var val, ret, fn = jQuery.isFunction( elem[ type ] || null ),
176 // Check to see if we need to provide a fake event, or not
177 event = !data[0] || !data[0].preventDefault;
179 // Pass along a fake event
181 data.unshift( this.fix({ type: type, target: elem }) );
183 // Enforce the right trigger type
187 if ( jQuery.isFunction( jQuery.data(elem, "handle") ) )
188 val = jQuery.data(elem, "handle").apply( elem, data );
190 // Handle triggering native .onfoo handlers
191 if ( !fn && elem["on"+type] && elem["on"+type].apply( elem, data ) === false )
194 // Extra functions don't get the custom event object
198 // Handle triggering of extra function
200 // call the extra function and tack the current return value on the end for possible inspection
201 var ret = extra.apply( elem, data.concat( val ) );
202 // if anything is returned, give it precedence and have it overwrite the previous value
203 if (ret !== undefined)
207 // Trigger the native events (except for clicks on links)
208 if ( fn && donative !== false && val !== false && !(jQuery.nodeName(elem, 'a') && type == "click") ) {
209 this.triggered = true;
212 // prevent IE from throwing an error for some hidden elements
216 this.triggered = false;
222 handle: function(event) {
223 // returned undefined or false
226 // Empty object is for triggered events with no data
227 event = jQuery.event.fix( event || window.event || {} );
229 // Namespaced event handlers
230 var parts = event.type.split(".");
231 event.type = parts[0];
233 var handlers = jQuery.data(this, "events") && jQuery.data(this, "events")[event.type], args = Array.prototype.slice.call( arguments, 1 );
234 args.unshift( event );
236 for ( var j in handlers ) {
237 var handler = handlers[j];
238 // Pass in a reference to the handler function itself
239 // So that we can later remove it
240 args[0].handler = handler;
241 args[0].data = handler.data;
243 // Filter the functions by class
244 if ( !parts[1] || handler.type == parts[1] ) {
245 var ret = handler.apply( this, args );
250 if ( ret === false ) {
251 event.preventDefault();
252 event.stopPropagation();
257 // Clean up added properties in IE to prevent memory leak
258 if (jQuery.browser.msie)
259 event.target = event.preventDefault = event.stopPropagation =
260 event.handler = event.data = null;
265 fix: function(event) {
266 // store a copy of the original event object
267 // and clone to set read-only properties
268 var originalEvent = event;
269 event = jQuery.extend({}, originalEvent);
271 // add preventDefault and stopPropagation since
272 // they will not work on the clone
273 event.preventDefault = function() {
274 // if preventDefault exists run it on the original event
275 if (originalEvent.preventDefault)
276 originalEvent.preventDefault();
277 // otherwise set the returnValue property of the original event to false (IE)
278 originalEvent.returnValue = false;
280 event.stopPropagation = function() {
281 // if stopPropagation exists run it on the original event
282 if (originalEvent.stopPropagation)
283 originalEvent.stopPropagation();
284 // otherwise set the cancelBubble property of the original event to true (IE)
285 originalEvent.cancelBubble = true;
288 // Fix target property, if necessary
290 event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either
292 // check if target is a textnode (safari)
293 if ( event.target.nodeType == 3 )
294 event.target = originalEvent.target.parentNode;
296 // Add relatedTarget, if necessary
297 if ( !event.relatedTarget && event.fromElement )
298 event.relatedTarget = event.fromElement == event.target ? event.toElement : event.fromElement;
300 // Calculate pageX/Y if missing and clientX/Y available
301 if ( event.pageX == null && event.clientX != null ) {
302 var doc = document.documentElement, body = document.body;
303 event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc.clientLeft || 0);
304 event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc.clientTop || 0);
307 // Add which for key events
308 if ( !event.which && (event.charCode || event.keyCode) )
309 event.which = event.charCode || event.keyCode;
311 // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
312 if ( !event.metaKey && event.ctrlKey )
313 event.metaKey = event.ctrlKey;
315 // Add which for click: 1 == left; 2 == middle; 3 == right
316 // Note: button is not normalized, so don't use it
317 if ( !event.which && event.button )
318 event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
326 var handler = jQuery.event.special.ready.handler;
328 // Mozilla, Opera and webkit nightlies currently support this event
329 if ( document.addEventListener )
330 // Use the handy event callback
331 document.addEventListener( "DOMContentLoaded", handler, false );
333 // If Safari or IE is used
334 // Continually check to see if the document is ready
335 if ((jQuery.browser.msie && window == top) || jQuery.browser.safari ) (function(){
337 // If IE is used, use the trick by Diego Perini
338 // http://javascript.nwbox.com/IEContentLoaded/
339 if ( jQuery.browser.msie || document.readyState != "loaded" && document.readyState != "complete" )
340 document.documentElement.doScroll("left");
342 setTimeout( arguments.callee, 0 );
346 // and execute any waiting functions
350 // A fallback to window.onload, that will always work
351 jQuery.event.add( window, "load", handler );
354 teardown: function() {return;},
356 handler: function() {
357 // Make sure that the DOM is not already loaded
358 if ( !jQuery.isReady ) {
359 // Remember that the DOM is ready
360 jQuery.isReady = true;
361 jQuery(document).triggerHandler("ready");
362 jQuery(document).unbind("ready");
369 if ( jQuery.browser.msie ) return false;
370 jQuery(this).bind("mouseover", jQuery.event.special.mouseenter.handler);
374 teardown: function() {
375 if ( jQuery.browser.msie ) return false;
376 jQuery(this).unbind("mouseover", jQuery.event.special.mouseenter.handler);
380 handler: function(event) {
381 // If we actually just moused on to a sub-element, ignore it
382 if ( withinElement(event, this) ) return true;
383 // Execute the right handlers by setting the event type to mouseenter
384 arguments[0].type = "mouseenter";
385 return jQuery.event.handle.apply(this, arguments);
391 if ( jQuery.browser.msie ) return false;
392 jQuery(this).bind("mouseout", jQuery.event.special.mouseleave.handler);
396 teardown: function() {
397 if ( jQuery.browser.msie ) return false;
398 jQuery(this).unbind("mouseout", jQuery.event.special.mouseleave.handler);
402 handler: function(event) {
403 // If we actually just moused on to a sub-element, ignore it
404 if ( withinElement(event, this) ) return true;
405 // Execute the right handlers by setting the event type to mouseleave
406 arguments[0].type = "mouseleave";
407 return jQuery.event.handle.apply(this, arguments);
414 bind: function( type, data, fn ) {
415 return type == "unload" ? this.one(type, data, fn) : this.each(function(){
416 jQuery.event.add( this, type, fn || data, fn && data );
420 one: function( type, data, fn ) {
421 return this.each(function(){
422 jQuery.event.add( this, type, function(event) {
423 jQuery(this).unbind(event);
424 return (fn || data).apply( this, arguments);
429 unbind: function( type, fn ) {
430 return this.each(function(){
431 jQuery.event.remove( this, type, fn );
435 trigger: function( type, data, fn ) {
436 return this.each(function(){
437 jQuery.event.trigger( type, data, this, true, fn );
441 triggerHandler: function( type, data, fn ) {
443 return jQuery.event.trigger( type, data, this[0], false, fn );
448 // Save reference to arguments for access in closure
449 var args = arguments;
451 return this.click(function(event) {
452 // Figure out which function to execute
453 this.lastToggle = 0 == this.lastToggle ? 1 : 0;
455 // Make sure that clicks stop
456 event.preventDefault();
458 // and execute the function
459 return args[this.lastToggle].apply( this, arguments ) || false;
463 hover: function(fnOver, fnOut) {
464 return this.bind('mouseenter', fnOver).bind('mouseleave', fnOut);
472 jQuery.each( ("blur,focus,load,ready,resize,scroll,unload,click,dblclick," +
473 "mousedown,mouseup,mousemove,mouseover,mouseout,change,select," +
474 "submit,keydown,keypress,keyup,error").split(","), function(i, name){
476 // Handle event binding
477 jQuery.fn[name] = function(fn){
478 return fn ? this.bind(name, fn) : this.trigger(name);
482 // Checks if an event happened on an element within another element
483 // Used in jQuery.event.special.mouseenter and mouseleave handlers
484 var withinElement = function(event, elem) {
485 // Check if mouse(over|out) are still within the same parent element
486 var parent = event.relatedTarget;
487 // Traverse up the tree
488 while ( parent && parent != elem ) try { parent = parent.parentNode } catch(error) { parent = elem; };
489 // Return true if we actually just moused on to a sub-element
490 return parent == elem;
493 // Prevent memory leaks in IE
494 // And prevent errors on refresh with events like mouseover in other browsers
495 // Window isn't included so as not to unbind existing unload events
496 jQuery(window).bind("unload", function() {
497 jQuery("*").add(document).unbind();