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 // Handle the second event of a trigger and when
45 // an event is called after a page has unloaded
46 if ( typeof jQuery != "undefined" && !jQuery.event.triggered )
47 return jQuery.event.handle.apply(arguments.callee.elem, arguments);
49 // Add elem as a property of the handle function
50 // This is to prevent a memory leak with non-native
54 // Handle multiple events seperated by a space
55 // jQuery(...).bind("mouseover mouseout", fn);
56 jQuery.each(types.split(/\s+/), function(index, type) {
57 // Namespaced event handlers
58 var parts = type.split(".");
60 handler.type = parts[1];
62 // Get the current list of functions bound to this event
63 var handlers = events[type];
65 // Init the event handler queue
67 handlers = events[type] = {};
69 // Check for a special event handler
70 // Only use addEventListener/attachEvent if the special
71 // events handler returns false
72 if ( !jQuery.event.special[type] || jQuery.event.special[type].setup.call(elem) === false ) {
73 // Bind the global event handler to the element
74 if (elem.addEventListener)
75 elem.addEventListener(type, handle, false);
76 else if (elem.attachEvent)
77 elem.attachEvent("on" + type, handle);
81 // Add the function to the element's handler list
82 handlers[handler.guid] = handler;
84 // Keep track of which events have been used, for global triggering
85 jQuery.event.global[type] = true;
88 // Nullify elem to prevent memory leaks in IE
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
105 if ( types == undefined || (typeof types == "string" && types.charAt(0) == ".") )
106 for ( var type in events )
107 this.remove( elem, type + (types || "") );
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(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 var handle = jQuery.data( elem, "handle" );
154 if ( handle ) handle.elem = null;
155 jQuery.removeData( elem, "events" );
156 jQuery.removeData( elem, "handle" );
161 trigger: function(type, data, elem, donative, extra) {
162 // Clone the incoming data, if any
163 data = jQuery.makeArray(data);
165 if ( type.indexOf("!") >= 0 ) {
166 type = type.slice(0, -1);
167 var exclusive = true;
170 // Handle a global trigger
172 // Only trigger if we've ever bound an event for it
173 if ( this.global[type] )
174 jQuery("*").add([window, document]).trigger(type, data);
176 // Handle triggering a single element
178 // don't do events on text and comment nodes
179 if ( elem.nodeType == 3 || elem.nodeType == 8 )
182 var val, ret, fn = jQuery.isFunction( elem[ type ] || null ),
183 // Check to see if we need to provide a fake event, or not
184 event = !data[0] || !data[0].preventDefault;
186 // Pass along a fake event
188 data.unshift( this.fix({ type: type, target: elem }) );
190 // Enforce the right trigger type
193 data[0].exclusive = true;
195 // Trigger the event, it is assumed that "handle" is a function
196 var handle = jQuery.data(elem, "handle");
198 val = handle.apply( elem, data );
200 // Handle triggering native .onfoo handlers (and on links since we don't call .click() for links)
201 if ( (!fn || (jQuery.nodeName(elem, 'a') && type == "click")) && elem["on"+type] && elem["on"+type].apply( elem, data ) === false )
204 // Extra functions don't get the custom event object
208 // Handle triggering of extra function
209 if ( extra && jQuery.isFunction( extra ) ) {
210 // call the extra function and tack the current return value on the end for possible inspection
211 ret = extra.apply( elem, val == null ? data : data.concat( val ) );
212 // if anything is returned, give it precedence and have it overwrite the previous value
213 if (ret !== undefined)
217 // Trigger the native events (except for clicks on links)
218 if ( fn && donative !== false && val !== false && !(jQuery.nodeName(elem, 'a') && type == "click") ) {
219 this.triggered = true;
222 // prevent IE from throwing an error for some hidden elements
226 this.triggered = false;
232 handle: function(event) {
233 // returned undefined or false
234 var val, ret, namespace, all, handlers;
236 event = arguments[0] = jQuery.event.fix( event || window.event );
238 // Namespaced event handlers
239 namespace = event.type.split(".");
240 event.type = namespace[0];
241 namespace = namespace[1];
242 all = !namespace && !event.exclusive; //cache this now, all = true means, any handler
244 handlers = ( jQuery.data(this, "events") || {} )[event.type];
246 for ( var j in handlers ) {
247 var handler = handlers[j];
249 // Filter the functions by class
250 if ( all || handler.type == namespace ) {
251 // Pass in a reference to the handler function itself
252 // So that we can later remove it
253 event.handler = handler;
254 event.data = handler.data;
256 ret = handler.apply( this, arguments );
261 if ( ret === false ) {
262 event.preventDefault();
263 event.stopPropagation();
268 // Clean up added properties in IE to prevent memory leak
269 if (jQuery.browser.msie)
270 event.target = event.preventDefault = event.stopPropagation =
271 event.handler = event.data = null;
276 fix: function(event) {
277 // store a copy of the original event object
278 // and clone to set read-only properties
279 var originalEvent = event;
280 event = jQuery.extend({}, originalEvent);
282 // add preventDefault and stopPropagation since
283 // they will not work on the clone
284 event.preventDefault = function() {
285 // if preventDefault exists run it on the original event
286 if (originalEvent.preventDefault)
287 originalEvent.preventDefault();
288 // otherwise set the returnValue property of the original event to false (IE)
289 originalEvent.returnValue = false;
291 event.stopPropagation = function() {
292 // if stopPropagation exists run it on the original event
293 if (originalEvent.stopPropagation)
294 originalEvent.stopPropagation();
295 // otherwise set the cancelBubble property of the original event to true (IE)
296 originalEvent.cancelBubble = true;
300 event.timeStamp = event.timeStamp || +new Date;
302 // Fix target property, if necessary
304 event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either
306 // check if target is a textnode (safari)
307 if ( event.target.nodeType == 3 )
308 event.target = originalEvent.target.parentNode;
310 // Add relatedTarget, if necessary
311 if ( !event.relatedTarget && event.fromElement )
312 event.relatedTarget = event.fromElement == event.target ? event.toElement : event.fromElement;
314 // Calculate pageX/Y if missing and clientX/Y available
315 if ( event.pageX == null && event.clientX != null ) {
316 var doc = document.documentElement, body = document.body;
317 event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc.clientLeft || 0);
318 event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc.clientTop || 0);
321 // Add which for key events
322 if ( !event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode) )
323 event.which = event.charCode || event.keyCode;
325 // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
326 if ( !event.metaKey && event.ctrlKey )
327 event.metaKey = event.ctrlKey;
329 // Add which for click: 1 == left; 2 == middle; 3 == right
330 // Note: button is not normalized, so don't use it
331 if ( !event.which && event.button )
332 event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
340 // Make sure the ready event is setup
345 teardown: function() { return; }
350 if ( jQuery.browser.msie ) return false;
351 jQuery(this).bind("mouseover", jQuery.event.special.mouseenter.handler);
355 teardown: function() {
356 if ( jQuery.browser.msie ) return false;
357 jQuery(this).unbind("mouseover", jQuery.event.special.mouseenter.handler);
361 handler: function(event) {
362 // If we actually just moused on to a sub-element, ignore it
363 if ( withinElement(event, this) ) return true;
364 // Execute the right handlers by setting the event type to mouseenter
365 arguments[0].type = "mouseenter";
366 return jQuery.event.handle.apply(this, arguments);
372 if ( jQuery.browser.msie ) return false;
373 jQuery(this).bind("mouseout", jQuery.event.special.mouseleave.handler);
377 teardown: function() {
378 if ( jQuery.browser.msie ) return false;
379 jQuery(this).unbind("mouseout", jQuery.event.special.mouseleave.handler);
383 handler: function(event) {
384 // If we actually just moused on to a sub-element, ignore it
385 if ( withinElement(event, this) ) return true;
386 // Execute the right handlers by setting the event type to mouseleave
387 arguments[0].type = "mouseleave";
388 return jQuery.event.handle.apply(this, arguments);
395 bind: function( type, data, fn ) {
396 return type == "unload" ? this.one(type, data, fn) : this.each(function(){
397 jQuery.event.add( this, type, fn || data, fn && data );
401 one: function( type, data, fn ) {
402 return this.each(function(){
403 jQuery.event.add( this, type, function(event) {
404 jQuery(this).unbind(event);
405 return (fn || data).apply( this, arguments);
410 unbind: function( type, fn ) {
411 return this.each(function(){
412 jQuery.event.remove( this, type, fn );
416 trigger: function( type, data, fn ) {
417 return this.each(function(){
418 jQuery.event.trigger( type, data, this, true, fn );
422 triggerHandler: function( type, data, fn ) {
424 return jQuery.event.trigger( type, data, this[0], false, fn );
429 // Save reference to arguments for access in closure
430 var args = arguments;
432 return this.click(function(event) {
433 // Figure out which function to execute
434 this.lastToggle = 0 == this.lastToggle ? 1 : 0;
436 // Make sure that clicks stop
437 event.preventDefault();
439 // and execute the function
440 return args[this.lastToggle].apply( this, arguments ) || false;
444 hover: function(fnOver, fnOut) {
445 return this.bind('mouseenter', fnOver).bind('mouseleave', fnOut);
448 ready: function(fn) {
449 // Attach the listeners
452 // If the DOM is already ready
453 if ( jQuery.isReady )
454 // Execute the function immediately
455 fn.call( document, jQuery );
457 // Otherwise, remember the function for later
459 // Add the function to the wait list
460 jQuery.readyList.push( function() { return fn.call(this, jQuery); } );
469 // Handle when the DOM is ready
471 // Make sure that the DOM is not already loaded
472 if ( !jQuery.isReady ) {
473 // Remember that the DOM is ready
474 jQuery.isReady = true;
476 // If there are functions bound, to execute
477 if ( jQuery.readyList ) {
478 // Execute all of them
479 jQuery.each( jQuery.readyList, function(){
480 this.apply( document );
483 // Reset the list of functions
484 jQuery.readyList = null;
487 // Trigger any bound ready events
488 jQuery(document).triggerHandler("ready");
493 var readyBound = false;
495 function bindReady(){
496 if ( readyBound ) return;
499 // Mozilla, Opera (see further below for it) and webkit nightlies currently support this event
500 if ( document.addEventListener && !jQuery.browser.opera)
501 // Use the handy event callback
502 document.addEventListener( "DOMContentLoaded", jQuery.ready, false );
504 // If IE is used and is not in a frame
505 // Continually check to see if the document is ready
506 if ( jQuery.browser.msie && window == top ) (function(){
507 if (jQuery.isReady) return;
509 // If IE is used, use the trick by Diego Perini
510 // http://javascript.nwbox.com/IEContentLoaded/
511 document.documentElement.doScroll("left");
513 setTimeout( arguments.callee, 0 );
516 // and execute any waiting functions
520 if ( jQuery.browser.opera )
521 document.addEventListener( "DOMContentLoaded", function () {
522 if (jQuery.isReady) return;
523 for (var i = 0; i < document.styleSheets.length; i++)
524 if (document.styleSheets[i].disabled) {
525 setTimeout( arguments.callee, 0 );
528 // and execute any waiting functions
532 if ( jQuery.browser.safari ) {
535 if (jQuery.isReady) return;
536 if ( document.readyState != "loaded" && document.readyState != "complete" ) {
537 setTimeout( arguments.callee, 0 );
540 if ( numStyles === undefined )
541 numStyles = jQuery("style, link[rel=stylesheet]").length;
542 if ( document.styleSheets.length != numStyles ) {
543 setTimeout( arguments.callee, 0 );
546 // and execute any waiting functions
551 // A fallback to window.onload, that will always work
552 jQuery.event.add( window, "load", jQuery.ready );
555 jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
556 "mousedown,mouseup,mousemove,mouseover,mouseout,change,select," +
557 "submit,keydown,keypress,keyup,error").split(","), function(i, name){
559 // Handle event binding
560 jQuery.fn[name] = function(fn){
561 return fn ? this.bind(name, fn) : this.trigger(name);
565 // Checks if an event happened on an element within another element
566 // Used in jQuery.event.special.mouseenter and mouseleave handlers
567 var withinElement = function(event, elem) {
568 // Check if mouse(over|out) are still within the same parent element
569 var parent = event.relatedTarget;
570 // Traverse up the tree
571 while ( parent && parent != elem ) try { parent = parent.parentNode; } catch(error) { parent = elem; }
572 // Return true if we actually just moused on to a sub-element
573 return parent == elem;
576 // Prevent memory leaks in IE
577 // And prevent errors on refresh with events like mouseover in other browsers
578 // Window isn't included so as not to unbind existing unload events
579 jQuery(window).bind("unload", function() {
580 jQuery("*").add(document).unbind();