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;
199 this.triggered = false;
205 handle: function(event) {
206 // returned undefined or false
209 // Empty object is for triggered events with no data
210 event = jQuery.event.fix( event || window.event || {} );
212 // Namespaced event handlers
213 var parts = event.type.split(".");
214 event.type = parts[0];
216 var handlers = jQuery.data(this, "events") && jQuery.data(this, "events")[event.type], args = Array.prototype.slice.call( arguments, 1 );
217 args.unshift( event );
219 for ( var j in handlers ) {
220 var handler = handlers[j];
221 // Pass in a reference to the handler function itself
222 // So that we can later remove it
223 args[0].handler = handler;
224 args[0].data = handler.data;
226 // Filter the functions by class
227 if ( !parts[1] || handler.type == parts[1] ) {
228 var ret = handler.apply( this, args );
233 if ( ret === false ) {
234 event.preventDefault();
235 event.stopPropagation();
240 // Clean up added properties in IE to prevent memory leak
241 if (jQuery.browser.msie)
242 event.target = event.preventDefault = event.stopPropagation =
243 event.handler = event.data = null;
248 fix: function(event) {
249 // store a copy of the original event object
250 // and clone to set read-only properties
251 var originalEvent = event;
252 event = jQuery.extend({}, originalEvent);
254 // add preventDefault and stopPropagation since
255 // they will not work on the clone
256 event.preventDefault = function() {
257 // if preventDefault exists run it on the original event
258 if (originalEvent.preventDefault)
259 originalEvent.preventDefault();
260 // otherwise set the returnValue property of the original event to false (IE)
261 originalEvent.returnValue = false;
263 event.stopPropagation = function() {
264 // if stopPropagation exists run it on the original event
265 if (originalEvent.stopPropagation)
266 originalEvent.stopPropagation();
267 // otherwise set the cancelBubble property of the original event to true (IE)
268 originalEvent.cancelBubble = true;
271 // Fix target property, if necessary
273 event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either
275 // check if target is a textnode (safari)
276 if ( event.target.nodeType == 3 )
277 event.target = originalEvent.target.parentNode;
279 // Add relatedTarget, if necessary
280 if ( !event.relatedTarget && event.fromElement )
281 event.relatedTarget = event.fromElement == event.target ? event.toElement : event.fromElement;
283 // Calculate pageX/Y if missing and clientX/Y available
284 if ( event.pageX == null && event.clientX != null ) {
285 var doc = document.documentElement, body = document.body;
286 event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc.clientLeft || 0);
287 event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc.clientLeft || 0);
290 // Add which for key events
291 if ( !event.which && (event.charCode || event.keyCode) )
292 event.which = event.charCode || event.keyCode;
294 // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
295 if ( !event.metaKey && event.ctrlKey )
296 event.metaKey = event.ctrlKey;
298 // Add which for click: 1 == left; 2 == middle; 3 == right
299 // Note: button is not normalized, so don't use it
300 if ( !event.which && event.button )
301 event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
308 bind: function( type, data, fn ) {
309 return type == "unload" ? this.one(type, data, fn) : this.each(function(){
310 jQuery.event.add( this, type, fn || data, fn && data );
314 one: function( type, data, fn ) {
315 return this.each(function(){
316 jQuery.event.add( this, type, function(event) {
317 jQuery(this).unbind(event);
318 return (fn || data).apply( this, arguments);
323 unbind: function( type, fn ) {
324 return this.each(function(){
325 jQuery.event.remove( this, type, fn );
329 trigger: function( type, data, fn ) {
330 return this.each(function(){
331 jQuery.event.trigger( type, data, this, true, fn );
335 triggerHandler: function( type, data, fn ) {
337 return jQuery.event.trigger( type, data, this[0], false, fn );
341 // Save reference to arguments for access in closure
342 var args = arguments;
344 return this.click(function(event) {
345 // Figure out which function to execute
346 this.lastToggle = 0 == this.lastToggle ? 1 : 0;
348 // Make sure that clicks stop
349 event.preventDefault();
351 // and execute the function
352 return args[this.lastToggle].apply( this, arguments ) || false;
356 hover: function(fnOver, fnOut) {
358 // A private function for handling mouse 'hovering'
359 function handleHover(event) {
360 // Check if mouse(over|out) are still within the same parent element
361 var parent = event.relatedTarget;
363 // Traverse up the tree
364 while ( parent && parent != this ) try { parent = parent.parentNode; } catch(error) { parent = this; };
366 // If we actually just moused on to a sub-element, ignore it
367 if ( parent == this )
370 // Execute the right function
371 return (event.type == "mouseover" ? fnOver : fnOut).apply(this, [event]);
374 // Bind the function to the two event listeners
375 return this.mouseover(handleHover).mouseout(handleHover);
378 ready: function(fn) {
379 // Attach the listeners
382 // If the DOM is already ready
383 if ( jQuery.isReady )
384 // Execute the function immediately
385 fn.apply( document, [jQuery] );
387 // Otherwise, remember the function for later
389 // Add the function to the wait list
390 jQuery.readyList.push( function() { return fn.apply(this, [jQuery]); } );
398 * All the code that makes DOM Ready work nicely.
403 // Handle when the DOM is ready
405 // Make sure that the DOM is not already loaded
406 if ( !jQuery.isReady ) {
407 // Remember that the DOM is ready
408 jQuery.isReady = true;
410 // If there are functions bound, to execute
411 if ( jQuery.readyList ) {
412 // Execute all of them
413 jQuery.each( jQuery.readyList, function(){
414 this.apply( document );
417 // Reset the list of functions
418 jQuery.readyList = null;
420 // Remove event listener to avoid memory leak
421 if ( document.removeEventListener )
422 document.removeEventListener( "DOMContentLoaded", jQuery.ready, false );
428 jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
429 "mousedown,mouseup,mousemove,mouseover,mouseout,change,select," +
430 "submit,keydown,keypress,keyup,error").split(","), function(i, name){
432 // Handle event binding
433 jQuery.fn[name] = function(fn){
434 return fn ? this.bind(name, fn) : this.trigger(name);
438 var readyBound = false;
440 function bindReady(){
441 if ( readyBound ) return;
444 // Mozilla, Opera and webkit nightlies currently support this event
445 if ( document.addEventListener )
446 // Use the handy event callback
447 document.addEventListener( "DOMContentLoaded", jQuery.ready, false );
449 // If Safari or IE is used
450 // Continually check to see if the document is ready
451 if (jQuery.browser.msie || jQuery.browser.safari ) (function(){
453 // If IE is used, use the trick by Diego Perini
454 // http://javascript.nwbox.com/IEContentLoaded/
455 if ( jQuery.browser.msie || document.readyState != "loaded" && document.readyState != "complete" )
456 document.documentElement.doScroll("left");
458 return setTimeout( arguments.callee, 0 );
461 // and execute any waiting functions
465 // A fallback to window.onload, that will always work
466 jQuery.event.add( window, "load", jQuery.ready );
469 // Prevent memory leaks in IE
470 // And prevent errors on refresh with events like mouseover
471 // Window isn't included so as not to unbind existing unload events
472 jQuery(window).bind("unload", function() {
473 jQuery("*").add(document).unbind();