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 // For whatever reason, IE has trouble passing the window object
12 // around, causing it to be cloned in the process
13 if ( jQuery.browser.msie && element.setInterval != undefined )
16 // if data is passed, bind to handler
17 if( data != undefined ) {
18 // Create temporary function pointer to original handler
21 // Create unique handler function, wrapped around original handler
22 handler = function() {
23 // Pass arguments and context to original handler
24 return fn.apply(this, arguments);
27 // Store data in unique handler
30 // Set the guid of unique handler to the same of original handler, so it can be removed
31 handler.guid = fn.guid;
34 // Make sure that the function being executed has a unique ID
35 if ( !handler.guid ) {
36 handler.guid = this.guid++;
37 // Don't forget to set guid for the original handler function
38 if (fn) fn.guid = handler.guid;
41 // Init the element's event structure
46 element.$handle = function() {
47 jQuery.event.handle.apply(element, arguments);
50 // Get the current list of functions bound to this event
51 var handlers = element.$events[type];
53 // Init the event handler queue
55 handlers = element.$events[type] = {};
57 // And bind the global event handler to the element
58 if (element.addEventListener)
59 element.addEventListener(type, element.$handle, false);
60 else if (element.attachEvent)
61 element.attachEvent("on" + type, element.$handle);
64 // Add the function to the element's handler list
65 handlers[handler.guid] = handler;
67 // Remember the function in a global list (for triggering)
68 if (!this.global[type])
69 this.global[type] = [];
70 this.global[type].push( element );
76 // Detach an event or set of events from an element
77 remove: function(element, type, handler) {
78 var events = element.$events, ret;
81 // type is actually an event object here
82 if ( type && type.type ) {
83 handler = type.handler;
88 for ( type in events )
89 this.remove( element, type );
91 } else if ( events[type] ) {
92 // remove the given handler for the given type
94 delete events[type][handler.guid];
96 // remove all handlers for the given type
98 for ( handler in element.$events[type] )
99 delete events[type][handler];
101 // remove generic event handler if no more handlers exist
102 for ( ret in events[type] ) break;
104 if (element.removeEventListener)
105 element.removeEventListener(type, element.$handle, false);
106 else if (element.detachEvent)
107 element.detachEvent("on" + type, element.$handle);
113 // Remove the expando if it's no longer used
114 for ( ret in events ) break;
116 element.$handle = element.$events = null;
120 trigger: function(type, data, element) {
121 // Clone the incoming data, if any
122 data = jQuery.makeArray(data || []);
124 // Handle a global trigger
126 jQuery.each( this.global[type] || [], function(){
127 jQuery.event.trigger( type, data, this );
130 // Handle triggering a single element
132 var val, ret, fn = jQuery.isFunction( element[ type ] || null );
134 // Pass along a fake event
135 data.unshift( this.fix({ type: type, target: element }) );
138 if ( (val = this.handle.apply( element, data )) !== false )
139 this.triggered = true;
141 if ( fn && val !== false && !jQuery.nodeName(element, 'a') )
144 this.triggered = false;
148 handle: function(event) {
149 // returned undefined or false
152 // Handle the second event of a trigger and when
153 // an event is called after a page has unloaded
154 if ( typeof jQuery == "undefined" || jQuery.event.triggered )
157 // Empty object is for triggered events with no data
158 event = jQuery.event.fix( event || window.event || {} );
160 var c = this.$events && this.$events[event.type], args = [].slice.call( arguments, 1 );
161 args.unshift( event );
164 // Pass in a reference to the handler function itself
165 // So that we can later remove it
166 args[0].handler = c[j];
167 args[0].data = c[j].data;
169 if ( c[j].apply( this, args ) === false ) {
170 event.preventDefault();
171 event.stopPropagation();
176 // Clean up added properties in IE to prevent memory leak
177 if (jQuery.browser.msie)
178 event.target = event.preventDefault = event.stopPropagation =
179 event.handler = event.data = null;
184 fix: function(event) {
185 // Fix target property, if necessary
186 if ( !event.target && event.srcElement )
187 event.target = event.srcElement;
189 // Calculate pageX/Y if missing and clientX/Y available
190 if ( event.pageX == undefined && event.clientX != undefined ) {
191 var e = document.documentElement || document.body;
192 event.pageX = event.clientX + e.scrollLeft;
193 event.pageY = event.clientY + e.scrollTop;
196 // check if target is a textnode (safari)
197 if (jQuery.browser.safari && event.target.nodeType == 3) {
198 // store a copy of the original event object
199 // and clone because target is read only
200 var originalEvent = event;
201 event = jQuery.extend({}, originalEvent);
203 // get parentnode from textnode
204 event.target = originalEvent.target.parentNode;
206 // add preventDefault and stopPropagation since
207 // they will not work on the clone
208 event.preventDefault = function() {
209 return originalEvent.preventDefault();
211 event.stopPropagation = function() {
212 return originalEvent.stopPropagation();
216 // fix preventDefault and stopPropagation
217 if (!event.preventDefault)
218 event.preventDefault = function() {
219 this.returnValue = false;
222 if (!event.stopPropagation)
223 event.stopPropagation = function() {
224 this.cancelBubble = true;
234 * Binds a handler to a particular event (like click) for each matched element.
235 * The event handler is passed an event object that you can use to prevent
236 * default behaviour. To stop both default action and event bubbling, your handler
237 * has to return false.
239 * In most cases, you can define your event handlers as anonymous functions
240 * (see first example). In cases where that is not possible, you can pass additional
241 * data as the second parameter (and the handler function as the third), see
244 * @example $("p").bind("click", function(){
245 * alert( $(this).text() );
247 * @before <p>Hello</p>
248 * @result alert("Hello")
250 * @example function handler(event) {
251 * alert(event.data.foo);
253 * $("p").bind("click", {foo: "bar"}, handler)
254 * @result alert("bar")
255 * @desc Pass some additional data to the event handler.
257 * @example $("form").bind("submit", function() { return false; })
258 * @desc Cancel a default action and prevent it from bubbling by returning false
259 * from your function.
261 * @example $("form").bind("submit", function(event){
262 * event.preventDefault();
264 * @desc Cancel only the default action by using the preventDefault method.
267 * @example $("form").bind("submit", function(event){
268 * event.stopPropagation();
270 * @desc Stop only an event from bubbling by using the stopPropagation method.
274 * @param String type An event type
275 * @param Object data (optional) Additional data passed to the event handler as event.data
276 * @param Function fn A function to bind to the event on each of the set of matched elements
279 bind: function( type, data, fn ) {
280 return this.each(function(){
281 jQuery.event.add( this, type, fn || data, fn && data );
286 * Binds a handler to a particular event (like click) for each matched element.
287 * The handler is executed only once for each element. Otherwise, the same rules
288 * as described in bind() apply.
289 The event handler is passed an event object that you can use to prevent
290 * default behaviour. To stop both default action and event bubbling, your handler
291 * has to return false.
293 * In most cases, you can define your event handlers as anonymous functions
294 * (see first example). In cases where that is not possible, you can pass additional
295 * data as the second paramter (and the handler function as the third), see
298 * @example $("p").one("click", function(){
299 * alert( $(this).text() );
301 * @before <p>Hello</p>
302 * @result alert("Hello")
306 * @param String type An event type
307 * @param Object data (optional) Additional data passed to the event handler as event.data
308 * @param Function fn A function to bind to the event on each of the set of matched elements
311 one: function( type, data, fn ) {
312 return this.each(function(){
313 jQuery.event.add( this, type, function(event) {
314 jQuery(this).unbind(event);
315 return (fn || data).apply( this, arguments);
321 * The opposite of bind, removes a bound event from each of the matched
324 * Without any arguments, all bound events are removed.
326 * If the type is provided, all bound events of that type are removed.
328 * If the function that was passed to bind is provided as the second argument,
329 * only that specific event handler is removed.
331 * @example $("p").unbind()
332 * @before <p onclick="alert('Hello');">Hello</p>
333 * @result [ <p>Hello</p> ]
335 * @example $("p").unbind( "click" )
336 * @before <p onclick="alert('Hello');">Hello</p>
337 * @result [ <p>Hello</p> ]
339 * @example $("p").unbind( "click", function() { alert("Hello"); } )
340 * @before <p onclick="alert('Hello');">Hello</p>
341 * @result [ <p>Hello</p> ]
345 * @param String type (optional) An event type
346 * @param Function fn (optional) A function to unbind from the event on each of the set of matched elements
349 unbind: function( type, fn ) {
350 return this.each(function(){
351 jQuery.event.remove( this, type, fn );
356 * Trigger a type of event on every matched element. This will also cause
357 * the default action of the browser with the same name (if one exists)
358 * to be executed. For example, passing 'submit' to the trigger()
359 * function will also cause the browser to submit the form. This
360 * default action can be prevented by returning false from one of
361 * the functions bound to the event.
363 * You can also trigger custom events registered with bind.
365 * @example $("p").trigger("click")
366 * @before <p click="alert('hello')">Hello</p>
367 * @result alert('hello')
369 * @example $("p").click(function(event, a, b) {
370 * // when a normal click fires, a and b are undefined
371 * // for a trigger like below a refers too "foo" and b refers to "bar"
372 * }).trigger("click", ["foo", "bar"]);
373 * @desc Example of how to pass arbitrary data to an event
375 * @example $("p").bind("myEvent",function(event,message1,message2) {
376 * alert(message1 + ' ' + message2);
378 * $("p").trigger("myEvent",["Hello","World"]);
379 * @result alert('Hello World') // One for each paragraph
383 * @param String type An event type to trigger.
384 * @param Array data (optional) Additional data to pass as arguments (after the event object) to the event handler
387 trigger: function( type, data ) {
388 return this.each(function(){
389 jQuery.event.trigger( type, data, this );
394 * Toggle between two function calls every other click.
395 * Whenever a matched element is clicked, the first specified function
396 * is fired, when clicked again, the second is fired. All subsequent
397 * clicks continue to rotate through the two functions.
399 * Use unbind("click") to remove.
401 * @example $("p").toggle(function(){
402 * $(this).addClass("selected");
404 * $(this).removeClass("selected");
409 * @param Function even The function to execute on every even click.
410 * @param Function odd The function to execute on every odd click.
414 // Save reference to arguments for access in closure
417 return this.click(function(e) {
418 // Figure out which function to execute
419 this.lastToggle = 0 == this.lastToggle ? 1 : 0;
421 // Make sure that clicks stop
424 // and execute the function
425 return a[this.lastToggle].apply( this, [e] ) || false;
430 * A method for simulating hovering (moving the mouse on, and off,
431 * an object). This is a custom method which provides an 'in' to a
434 * Whenever the mouse cursor is moved over a matched
435 * element, the first specified function is fired. Whenever the mouse
436 * moves off of the element, the second specified function fires.
437 * Additionally, checks are in place to see if the mouse is still within
438 * the specified element itself (for example, an image inside of a div),
439 * and if it is, it will continue to 'hover', and not move out
440 * (a common error in using a mouseout event handler).
442 * @example $("p").hover(function(){
443 * $(this).addClass("hover");
445 * $(this).removeClass("hover");
450 * @param Function over The function to fire whenever the mouse is moved over a matched element.
451 * @param Function out The function to fire whenever the mouse is moved off of a matched element.
454 hover: function(f,g) {
456 // A private function for handling mouse 'hovering'
457 function handleHover(e) {
458 // Check if mouse(over|out) are still within the same parent element
459 var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
461 // Traverse up the tree
462 while ( p && p != this ) try { p = p.parentNode } catch(e) { p = this; };
464 // If we actually just moused on to a sub-element, ignore it
465 if ( p == this ) return false;
467 // Execute the right function
468 return (e.type == "mouseover" ? f : g).apply(this, [e]);
471 // Bind the function to the two event listeners
472 return this.mouseover(handleHover).mouseout(handleHover);
476 * Bind a function to be executed whenever the DOM is ready to be
477 * traversed and manipulated. This is probably the most important
478 * function included in the event module, as it can greatly improve
479 * the response times of your web applications.
481 * In a nutshell, this is a solid replacement for using window.onload,
482 * and attaching a function to that. By using this method, your bound function
483 * will be called the instant the DOM is ready to be read and manipulated,
484 * which is when what 99.99% of all JavaScript code needs to run.
486 * There is one argument passed to the ready event handler: A reference to
487 * the jQuery function. You can name that argument whatever you like, and
488 * can therefore stick with the $ alias without risk of naming collisions.
490 * Please ensure you have no code in your <body> onload event handler,
491 * otherwise $(document).ready() may not fire.
493 * You can have as many $(document).ready events on your page as you like.
494 * The functions are then executed in the order they were added.
496 * @example $(document).ready(function(){ Your code here... });
498 * @example jQuery(function($) {
499 * // Your code using failsafe $ alias here...
501 * @desc Uses both the [[Core#.24.28_fn_.29|shortcut]] for $(document).ready() and the argument
502 * to write failsafe jQuery code using the $ alias, without relying on the
507 * @param Function fn The function to be executed when the DOM is ready.
509 * @see $.noConflict()
513 // If the DOM is already ready
514 if ( jQuery.isReady )
515 // Execute the function immediately
516 f.apply( document, [jQuery] );
518 // Otherwise, remember the function for later
520 // Add the function to the wait list
521 jQuery.readyList.push( function() { return f.apply(this, [jQuery]) } );
530 * All the code that makes DOM Ready work nicely.
535 // Handle when the DOM is ready
537 // Make sure that the DOM is not already loaded
538 if ( !jQuery.isReady ) {
539 // Remember that the DOM is ready
540 jQuery.isReady = true;
542 // If there are functions bound, to execute
543 if ( jQuery.readyList ) {
544 // Execute all of them
545 jQuery.each( jQuery.readyList, function(){
546 this.apply( document );
549 // Reset the list of functions
550 jQuery.readyList = null;
552 // Remove event lisenter to avoid memory leak
553 if ( jQuery.browser.mozilla || jQuery.browser.opera )
554 document.removeEventListener( "DOMContentLoaded", jQuery.ready, false );
556 // Remove script element used by IE hack
557 jQuery(window).load(function(){ jQuery("#__ie_init").remove(); });
565 * Bind a function to the scroll event of each matched element.
567 * @example $("p").scroll( function() { alert("Hello"); } );
568 * @before <p>Hello</p>
569 * @result <p onscroll="alert('Hello');">Hello</p>
573 * @param Function fn A function to bind to the scroll event on each of the matched elements.
578 * Bind a function to the submit event of each matched element.
580 * @example $("#myform").submit( function() {
581 * return $("input", this).val().length > 0;
583 * @before <form id="myform"><input /></form>
584 * @desc Prevents the form submission when the input has no value entered.
588 * @param Function fn A function to bind to the submit event on each of the matched elements.
593 * Trigger the submit event of each matched element. This causes all of the functions
594 * that have been bound to that submit event to be executed, and calls the browser's
595 * default submit action on the matching element(s). This default action can be prevented
596 * by returning false from one of the functions bound to the submit event.
598 * Note: This does not execute the submit method of the form element! If you need to
599 * submit the form via code, you have to use the DOM method, eg. $("form")[0].submit();
601 * @example $("form").submit();
602 * @desc Triggers all submit events registered to the matched form(s), and submits them.
610 * Bind a function to the focus event of each matched element.
612 * @example $("p").focus( function() { alert("Hello"); } );
613 * @before <p>Hello</p>
614 * @result <p onfocus="alert('Hello');">Hello</p>
618 * @param Function fn A function to bind to the focus event on each of the matched elements.
623 * Trigger the focus event of each matched element. This causes all of the functions
624 * that have been bound to thet focus event to be executed.
626 * Note: This does not execute the focus method of the underlying elements! If you need to
627 * focus an element via code, you have to use the DOM method, eg. $("#myinput")[0].focus();
629 * @example $("p").focus();
630 * @before <p onfocus="alert('Hello');">Hello</p>
631 * @result alert('Hello');
639 * Bind a function to the keydown event of each matched element.
641 * @example $("p").keydown( function() { alert("Hello"); } );
642 * @before <p>Hello</p>
643 * @result <p onkeydown="alert('Hello');">Hello</p>
647 * @param Function fn A function to bind to the keydown event on each of the matched elements.
652 * Bind a function to the dblclick event of each matched element.
654 * @example $("p").dblclick( function() { alert("Hello"); } );
655 * @before <p>Hello</p>
656 * @result <p ondblclick="alert('Hello');">Hello</p>
660 * @param Function fn A function to bind to the dblclick event on each of the matched elements.
665 * Bind a function to the keypress event of each matched element.
667 * @example $("p").keypress( function() { alert("Hello"); } );
668 * @before <p>Hello</p>
669 * @result <p onkeypress="alert('Hello');">Hello</p>
673 * @param Function fn A function to bind to the keypress event on each of the matched elements.
678 * Bind a function to the error event of each matched element.
680 * @example $("p").error( function() { alert("Hello"); } );
681 * @before <p>Hello</p>
682 * @result <p onerror="alert('Hello');">Hello</p>
686 * @param Function fn A function to bind to the error event on each of the matched elements.
691 * Bind a function to the blur event of each matched element.
693 * @example $("p").blur( function() { alert("Hello"); } );
694 * @before <p>Hello</p>
695 * @result <p onblur="alert('Hello');">Hello</p>
699 * @param Function fn A function to bind to the blur event on each of the matched elements.
704 * Trigger the blur event of each matched element. This causes all of the functions
705 * that have been bound to that blur event to be executed, and calls the browser's
706 * default blur action on the matching element(s). This default action can be prevented
707 * by returning false from one of the functions bound to the blur event.
709 * Note: This does not execute the blur method of the underlying elements! If you need to
710 * blur an element via code, you have to use the DOM method, eg. $("#myinput")[0].blur();
712 * @example $("p").blur();
713 * @before <p onblur="alert('Hello');">Hello</p>
714 * @result alert('Hello');
722 * Bind a function to the load event of each matched element.
724 * @example $("p").load( function() { alert("Hello"); } );
725 * @before <p>Hello</p>
726 * @result <p onload="alert('Hello');">Hello</p>
730 * @param Function fn A function to bind to the load event on each of the matched elements.
735 * Bind a function to the select event of each matched element.
737 * @example $("p").select( function() { alert("Hello"); } );
738 * @before <p>Hello</p>
739 * @result <p onselect="alert('Hello');">Hello</p>
743 * @param Function fn A function to bind to the select event on each of the matched elements.
748 * Trigger the select event of each matched element. This causes all of the functions
749 * that have been bound to that select event to be executed, and calls the browser's
750 * default select action on the matching element(s). This default action can be prevented
751 * by returning false from one of the functions bound to the select event.
753 * @example $("p").select();
754 * @before <p onselect="alert('Hello');">Hello</p>
755 * @result alert('Hello');
763 * Bind a function to the mouseup event of each matched element.
765 * @example $("p").mouseup( function() { alert("Hello"); } );
766 * @before <p>Hello</p>
767 * @result <p onmouseup="alert('Hello');">Hello</p>
771 * @param Function fn A function to bind to the mouseup event on each of the matched elements.
776 * Bind a function to the unload event of each matched element.
778 * @example $("p").unload( function() { alert("Hello"); } );
779 * @before <p>Hello</p>
780 * @result <p onunload="alert('Hello');">Hello</p>
784 * @param Function fn A function to bind to the unload event on each of the matched elements.
789 * Bind a function to the change event of each matched element.
791 * @example $("p").change( function() { alert("Hello"); } );
792 * @before <p>Hello</p>
793 * @result <p onchange="alert('Hello');">Hello</p>
797 * @param Function fn A function to bind to the change event on each of the matched elements.
802 * Bind a function to the mouseout event of each matched element.
804 * @example $("p").mouseout( function() { alert("Hello"); } );
805 * @before <p>Hello</p>
806 * @result <p onmouseout="alert('Hello');">Hello</p>
810 * @param Function fn A function to bind to the mouseout event on each of the matched elements.
815 * Bind a function to the keyup event of each matched element.
817 * @example $("p").keyup( function() { alert("Hello"); } );
818 * @before <p>Hello</p>
819 * @result <p onkeyup="alert('Hello');">Hello</p>
823 * @param Function fn A function to bind to the keyup event on each of the matched elements.
828 * Bind a function to the click event of each matched element.
830 * @example $("p").click( function() { alert("Hello"); } );
831 * @before <p>Hello</p>
832 * @result <p onclick="alert('Hello');">Hello</p>
836 * @param Function fn A function to bind to the click event on each of the matched elements.
841 * Trigger the click event of each matched element. This causes all of the functions
842 * that have been bound to thet click event to be executed.
844 * @example $("p").click();
845 * @before <p onclick="alert('Hello');">Hello</p>
846 * @result alert('Hello');
854 * Bind a function to the resize event of each matched element.
856 * @example $("p").resize( function() { alert("Hello"); } );
857 * @before <p>Hello</p>
858 * @result <p onresize="alert('Hello');">Hello</p>
862 * @param Function fn A function to bind to the resize event on each of the matched elements.
867 * Bind a function to the mousemove event of each matched element.
869 * @example $("p").mousemove( function() { alert("Hello"); } );
870 * @before <p>Hello</p>
871 * @result <p onmousemove="alert('Hello');">Hello</p>
875 * @param Function fn A function to bind to the mousemove event on each of the matched elements.
880 * Bind a function to the mousedown event of each matched element.
882 * @example $("p").mousedown( function() { alert("Hello"); } );
883 * @before <p>Hello</p>
884 * @result <p onmousedown="alert('Hello');">Hello</p>
888 * @param Function fn A function to bind to the mousedown event on each of the matched elements.
893 * Bind a function to the mouseover event of each matched element.
895 * @example $("p").mouseover( function() { alert("Hello"); } );
896 * @before <p>Hello</p>
897 * @result <p onmouseover="alert('Hello');">Hello</p>
901 * @param Function fn A function to bind to the mousedown event on each of the matched elements.
904 jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
905 "mousedown,mouseup,mousemove,mouseover,mouseout,change,select," +
906 "submit,keydown,keypress,keyup,error").split(","), function(i,o){
908 // Handle event binding
909 jQuery.fn[o] = function(f){
910 return f ? this.bind(o, f) : this.trigger(o);
915 // If Mozilla is used
916 if ( jQuery.browser.mozilla || jQuery.browser.opera )
917 // Use the handy event callback
918 document.addEventListener( "DOMContentLoaded", jQuery.ready, false );
920 // If IE is used, use the excellent hack by Matthias Miller
921 // http://www.outofhanwell.com/blog/index.php?title=the_window_onload_problem_revisited
922 else if ( jQuery.browser.msie ) {
924 // Only works if you document.write() it
925 document.write("<scr" + "ipt id=__ie_init defer=true " +
926 "src=//:><\/script>");
928 // Use the defer script hack
929 var script = document.getElementById("__ie_init");
931 // script does not exist if jQuery is loaded dynamically
933 script.onreadystatechange = function() {
934 if ( this.readyState != "complete" ) return;
942 } else if ( jQuery.browser.safari )
943 // Continually check to see if the document.readyState is valid
944 jQuery.safariTimer = setInterval(function(){
945 // loaded and complete are both valid states
946 if ( document.readyState == "loaded" ||
947 document.readyState == "complete" ) {
949 // If either one are found, remove the timer
950 clearInterval( jQuery.safariTimer );
951 jQuery.safariTimer = null;
953 // and execute any waiting functions
958 // A fallback to window.onload, that will always work
959 jQuery.event.add( window, "load", jQuery.ready );
963 // Clean up after IE to avoid memory leaks
964 if (jQuery.browser.msie)
965 jQuery(window).one("unload", function() {
966 var global = jQuery.event.global;
967 for ( var type in global ) {
968 var els = global[type], i = els.length;
969 if ( i && type != 'unload' )
971 jQuery.event.remove(els[i-1], type);