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(element, type, handler, data) {
11 if ( element.nodeType == 3 || element.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 && element.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 // Namespaced event handlers
42 var parts = type.split(".");
44 handler.type = parts[1];
46 // Init the element's event structure
47 var events = jQuery.data(element, "events") || jQuery.data(element, "events", {});
49 var handle = jQuery.data(element, "handle") || jQuery.data(element, "handle", function(){
50 // returned undefined or false
53 // Handle the second event of a trigger and when
54 // an event is called after a page has unloaded
55 if ( typeof jQuery == "undefined" || jQuery.event.triggered )
58 val = jQuery.event.handle.apply(element, arguments);
63 // Get the current list of functions bound to this event
64 var handlers = events[type];
66 // Init the event handler queue
68 handlers = events[type] = {};
70 // And bind the global event handler to the element
71 if (element.addEventListener)
72 element.addEventListener(type, handle, false);
74 element.attachEvent("on" + type, handle);
77 // Add the function to the element's handler list
78 handlers[handler.guid] = handler;
80 // Keep track of which events have been used, for global triggering
81 this.global[type] = true;
87 // Detach an event or set of events from an element
88 remove: function(element, type, handler) {
89 // don't do events on text and comment nodes
90 if ( element.nodeType == 3 || element.nodeType == 8 )
93 var events = jQuery.data(element, "events"), ret, index;
95 // Namespaced event handlers
96 if ( typeof type == "string" ) {
97 var parts = type.split(".");
102 // type is actually an event object here
103 if ( type && type.type ) {
104 handler = type.handler;
109 for ( type in events )
110 this.remove( element, type );
112 } else if ( events[type] ) {
113 // remove the given handler for the given type
115 delete events[type][handler.guid];
117 // remove all handlers for the given type
119 for ( handler in events[type] )
120 // Handle the removal of namespaced events
121 if ( !parts[1] || events[type][handler].type == parts[1] )
122 delete events[type][handler];
124 // remove generic event handler if no more handlers exist
125 for ( ret in events[type] ) break;
127 if (element.removeEventListener)
128 element.removeEventListener(type, jQuery.data(element, "handle"), false);
130 element.detachEvent("on" + type, jQuery.data(element, "handle"));
136 // Remove the expando if it's no longer used
137 for ( ret in events ) break;
139 jQuery.removeData( element, "events" );
140 jQuery.removeData( element, "handle" );
145 trigger: function(type, data, element, donative, extra) {
146 // Clone the incoming data, if any
147 data = jQuery.makeArray(data || []);
149 // Handle a global trigger
151 // Only trigger if we've ever bound an event for it
152 if ( this.global[type] )
153 jQuery("*").add([window, document]).trigger(type, data);
155 // Handle triggering a single element
157 // don't do events on text and comment nodes
158 if ( element.nodeType == 3 || element.nodeType == 8 )
161 var val, ret, fn = jQuery.isFunction( element[ type ] || null ),
162 // Check to see if we need to provide a fake event, or not
163 event = !data[0] || !data[0].preventDefault;
165 // Pass along a fake event
167 data.unshift( this.fix({ type: type, target: element }) );
169 // Enforce the right trigger type
173 if ( jQuery.isFunction( jQuery.data(element, "handle") ) )
174 val = jQuery.data(element, "handle").apply( element, data );
176 // Handle triggering native .onfoo handlers
177 if ( !fn && element["on"+type] && element["on"+type].apply( element, data ) === false )
180 // Extra functions don't get the custom event object
184 // Handle triggering of extra function
186 // call the extra function and tack the current return value on the end for possible inspection
187 var ret = extra.apply( element, data.concat( val ) );
188 // if anything is returned, give it precedence and have it overwrite the previous value
189 if (ret !== undefined)
193 // Trigger the native events (except for clicks on links)
194 if ( fn && donative !== false && val !== false && !(jQuery.nodeName(element, 'a') && type == "click") ) {
195 this.triggered = true;
198 // prevent IE from throwing an error for some hidden elements
202 this.triggered = false;
208 handle: function(event) {
209 // returned undefined or false
212 // Empty object is for triggered events with no data
213 event = jQuery.event.fix( event || window.event || {} );
215 // Namespaced event handlers
216 var parts = event.type.split(".");
217 event.type = parts[0];
219 var handlers = jQuery.data(this, "events") && jQuery.data(this, "events")[event.type], args = Array.prototype.slice.call( arguments, 1 );
220 args.unshift( event );
222 for ( var j in handlers ) {
223 var handler = handlers[j];
224 // Pass in a reference to the handler function itself
225 // So that we can later remove it
226 args[0].handler = handler;
227 args[0].data = handler.data;
229 // Filter the functions by class
230 if ( !parts[1] || handler.type == parts[1] ) {
231 var ret = handler.apply( this, args );
236 if ( ret === false ) {
237 event.preventDefault();
238 event.stopPropagation();
243 // Clean up added properties in IE to prevent memory leak
244 if (jQuery.browser.msie)
245 event.target = event.preventDefault = event.stopPropagation =
246 event.handler = event.data = null;
251 fix: function(event) {
252 // store a copy of the original event object
253 // and clone to set read-only properties
254 var originalEvent = event;
255 event = jQuery.extend({}, originalEvent);
257 // add preventDefault and stopPropagation since
258 // they will not work on the clone
259 event.preventDefault = function() {
260 // if preventDefault exists run it on the original event
261 if (originalEvent.preventDefault)
262 originalEvent.preventDefault();
263 // otherwise set the returnValue property of the original event to false (IE)
264 originalEvent.returnValue = false;
266 event.stopPropagation = function() {
267 // if stopPropagation exists run it on the original event
268 if (originalEvent.stopPropagation)
269 originalEvent.stopPropagation();
270 // otherwise set the cancelBubble property of the original event to true (IE)
271 originalEvent.cancelBubble = true;
274 // Fix target property, if necessary
276 event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either
278 // check if target is a textnode (safari)
279 if ( event.target.nodeType == 3 )
280 event.target = originalEvent.target.parentNode;
282 // Add relatedTarget, if necessary
283 if ( !event.relatedTarget && event.fromElement )
284 event.relatedTarget = event.fromElement == event.target ? event.toElement : event.fromElement;
286 // Calculate pageX/Y if missing and clientX/Y available
287 if ( event.pageX == null && event.clientX != null ) {
288 var doc = document.documentElement, body = document.body;
289 event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc.clientLeft || 0);
290 event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc.clientTop || 0);
293 // Add which for key events
294 if ( !event.which && (event.charCode || event.keyCode) )
295 event.which = event.charCode || event.keyCode;
297 // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
298 if ( !event.metaKey && event.ctrlKey )
299 event.metaKey = event.ctrlKey;
301 // Add which for click: 1 == left; 2 == middle; 3 == right
302 // Note: button is not normalized, so don't use it
303 if ( !event.which && event.button )
304 event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
311 bind: function( type, data, fn ) {
312 return type == "unload" ? this.one(type, data, fn) : this.each(function(){
313 jQuery.event.add( this, type, fn || data, fn && data );
317 one: function( type, data, fn ) {
318 return this.each(function(){
319 jQuery.event.add( this, type, function(event) {
320 jQuery(this).unbind(event);
321 return (fn || data).apply( this, arguments);
326 unbind: function( type, fn ) {
327 return this.each(function(){
328 jQuery.event.remove( this, type, fn );
332 trigger: function( type, data, fn ) {
333 return this.each(function(){
334 jQuery.event.trigger( type, data, this, true, fn );
338 triggerHandler: function( type, data, fn ) {
340 return jQuery.event.trigger( type, data, this[0], false, fn );
344 // Save reference to arguments for access in closure
345 var args = arguments;
347 return this.click(function(event) {
348 // Figure out which function to execute
349 this.lastToggle = 0 == this.lastToggle ? 1 : 0;
351 // Make sure that clicks stop
352 event.preventDefault();
354 // and execute the function
355 return args[this.lastToggle].apply( this, arguments ) || false;
359 hover: function(fnOver, fnOut) {
361 // A private function for handling mouse 'hovering'
362 function handleHover(event) {
363 // Check if mouse(over|out) are still within the same parent element
364 var parent = event.relatedTarget;
366 // Traverse up the tree
367 while ( parent && parent != this ) try { parent = parent.parentNode; } catch(error) { parent = this; };
369 // If we actually just moused on to a sub-element, ignore it
370 if ( parent == this )
373 // Execute the right function
374 return (event.type == "mouseover" ? fnOver : fnOut).apply(this, [event]);
377 // Bind the function to the two event listeners
378 return this.mouseover(handleHover).mouseout(handleHover);
381 ready: function(fn) {
382 // Attach the listeners
385 // If the DOM is already ready
386 if ( jQuery.isReady )
387 // Execute the function immediately
388 fn.apply( document, [jQuery] );
390 // Otherwise, remember the function for later
392 // Add the function to the wait list
393 jQuery.readyList.push( function() { return fn.apply(this, [jQuery]); } );
401 * All the code that makes DOM Ready work nicely.
406 // Handle when the DOM is ready
408 // Make sure that the DOM is not already loaded
409 if ( !jQuery.isReady ) {
410 // Remember that the DOM is ready
411 jQuery.isReady = true;
413 // If there are functions bound, to execute
414 if ( jQuery.readyList ) {
415 // Execute all of them
416 jQuery.each( jQuery.readyList, function(){
417 this.apply( document );
420 // Reset the list of functions
421 jQuery.readyList = null;
423 // Remove event listener to avoid memory leak
424 if ( document.removeEventListener )
425 document.removeEventListener( "DOMContentLoaded", jQuery.ready, false );
431 jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
432 "mousedown,mouseup,mousemove,mouseover,mouseout,change,select," +
433 "submit,keydown,keypress,keyup,error").split(","), function(i, name){
435 // Handle event binding
436 jQuery.fn[name] = function(fn){
437 return fn ? this.bind(name, fn) : this.trigger(name);
441 var readyBound = false;
443 function bindReady(){
444 if ( readyBound ) return;
447 // Mozilla, Opera and webkit nightlies currently support this event
448 if ( document.addEventListener )
449 // Use the handy event callback
450 document.addEventListener( "DOMContentLoaded", jQuery.ready, false );
452 // If Safari or IE is used
453 // Continually check to see if the document is ready
454 if (jQuery.browser.msie || jQuery.browser.safari ) (function(){
456 // If IE is used, use the trick by Diego Perini
457 // http://javascript.nwbox.com/IEContentLoaded/
458 if ( jQuery.browser.msie || document.readyState != "loaded" && document.readyState != "complete" )
459 document.documentElement.doScroll("left");
461 return setTimeout( arguments.callee, 0 );
464 // and execute any waiting functions
468 // A fallback to window.onload, that will always work
469 jQuery.event.add( window, "load", jQuery.ready );
472 // Prevent memory leaks in IE
473 // And prevent errors on refresh with events like mouseover
474 // Window isn't included so as not to unbind existing unload events
475 jQuery(window).bind("unload", function() {
476 jQuery("*").add(document).unbind();