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 ] );
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 // Handle the second event of a trigger and when
150 // an event is called after a page has unloaded
151 if ( typeof jQuery == "undefined" || jQuery.event.triggered ) return;
153 // Empty object is for triggered events with no data
154 event = jQuery.event.fix( event || window.event || {} );
156 // returned undefined or false
159 var c = this.$events[event.type];
161 var args = [].slice.call( arguments, 1 );
162 args.unshift( event );
165 // Pass in a reference to the handler function itself
166 // So that we can later remove it
167 args[0].handler = c[j];
168 args[0].data = c[j].data;
170 if ( c[j].apply( this, args ) === false ) {
171 event.preventDefault();
172 event.stopPropagation();
177 // Clean up added properties in IE to prevent memory leak
178 if (jQuery.browser.msie) event.target = event.preventDefault = event.stopPropagation = event.handler = event.data = null;
183 fix: function(event) {
184 // Fix target property, if necessary
185 if ( !event.target && event.srcElement )
186 event.target = event.srcElement;
188 // Calculate pageX/Y if missing and clientX/Y available
189 if ( event.pageX == undefined && event.clientX != undefined ) {
190 var e = document.documentElement, b = document.body;
191 event.pageX = event.clientX + (e.scrollLeft || b.scrollLeft);
192 event.pageY = event.clientY + (e.scrollTop || b.scrollTop);
195 // check if target is a textnode (safari)
196 if (jQuery.browser.safari && event.target.nodeType == 3) {
197 // store a copy of the original event object
198 // and clone because target is read only
199 var originalEvent = event;
200 event = jQuery.extend({}, originalEvent);
202 // get parentnode from textnode
203 event.target = originalEvent.target.parentNode;
205 // add preventDefault and stopPropagation since
206 // they will not work on the clone
207 event.preventDefault = function() {
208 return originalEvent.preventDefault();
210 event.stopPropagation = function() {
211 return originalEvent.stopPropagation();
215 // fix preventDefault and stopPropagation
216 if (!event.preventDefault)
217 event.preventDefault = function() {
218 this.returnValue = false;
221 if (!event.stopPropagation)
222 event.stopPropagation = function() {
223 this.cancelBubble = true;
233 * Binds a handler to a particular event (like click) for each matched element.
234 * The event handler is passed an event object that you can use to prevent
235 * default behaviour. To stop both default action and event bubbling, your handler
236 * has to return false.
238 * In most cases, you can define your event handlers as anonymous functions
239 * (see first example). In cases where that is not possible, you can pass additional
240 * data as the second parameter (and the handler function as the third), see
243 * @example $("p").bind("click", function(){
244 * alert( $(this).text() );
246 * @before <p>Hello</p>
247 * @result alert("Hello")
249 * @example function handler(event) {
250 * alert(event.data.foo);
252 * $("p").bind("click", {foo: "bar"}, handler)
253 * @result alert("bar")
254 * @desc Pass some additional data to the event handler.
256 * @example $("form").bind("submit", function() { return false; })
257 * @desc Cancel a default action and prevent it from bubbling by returning false
258 * from your function.
260 * @example $("form").bind("submit", function(event){
261 * event.preventDefault();
263 * @desc Cancel only the default action by using the preventDefault method.
266 * @example $("form").bind("submit", function(event){
267 * event.stopPropagation();
269 * @desc Stop only an event from bubbling by using the stopPropagation method.
273 * @param String type An event type
274 * @param Object data (optional) Additional data passed to the event handler as event.data
275 * @param Function fn A function to bind to the event on each of the set of matched elements
278 bind: function( type, data, fn ) {
279 return this.each(function(){
280 jQuery.event.add( this, type, fn || data, fn && data );
285 * Binds a handler to a particular event (like click) for each matched element.
286 * The handler is executed only once for each element. Otherwise, the same rules
287 * as described in bind() apply.
288 The event handler is passed an event object that you can use to prevent
289 * default behaviour. To stop both default action and event bubbling, your handler
290 * has to return false.
292 * In most cases, you can define your event handlers as anonymous functions
293 * (see first example). In cases where that is not possible, you can pass additional
294 * data as the second paramter (and the handler function as the third), see
297 * @example $("p").one("click", function(){
298 * alert( $(this).text() );
300 * @before <p>Hello</p>
301 * @result alert("Hello")
305 * @param String type An event type
306 * @param Object data (optional) Additional data passed to the event handler as event.data
307 * @param Function fn A function to bind to the event on each of the set of matched elements
310 one: function( type, data, fn ) {
311 return this.each(function(){
312 jQuery.event.add( this, type, function(event) {
313 jQuery(this).unbind(event);
314 return (fn || data).apply( this, arguments);
320 * The opposite of bind, removes a bound event from each of the matched
323 * Without any arguments, all bound events are removed.
325 * If the type is provided, all bound events of that type are removed.
327 * If the function that was passed to bind is provided as the second argument,
328 * only that specific event handler is removed.
330 * @example $("p").unbind()
331 * @before <p onclick="alert('Hello');">Hello</p>
332 * @result [ <p>Hello</p> ]
334 * @example $("p").unbind( "click" )
335 * @before <p onclick="alert('Hello');">Hello</p>
336 * @result [ <p>Hello</p> ]
338 * @example $("p").unbind( "click", function() { alert("Hello"); } )
339 * @before <p onclick="alert('Hello');">Hello</p>
340 * @result [ <p>Hello</p> ]
344 * @param String type (optional) An event type
345 * @param Function fn (optional) A function to unbind from the event on each of the set of matched elements
348 unbind: function( type, fn ) {
349 return this.each(function(){
350 jQuery.event.remove( this, type, fn );
355 * Trigger a type of event on every matched element. This will also cause
356 * the default action of the browser with the same name (if one exists)
357 * to be executed. For example, passing 'submit' to the trigger()
358 * function will also cause the browser to submit the form. This
359 * default action can be prevented by returning false from one of
360 * the functions bound to the event.
362 * You can also trigger custom events registered with bind.
364 * @example $("p").trigger("click")
365 * @before <p click="alert('hello')">Hello</p>
366 * @result alert('hello')
368 * @example $("p").click(function(event, a, b) {
369 * // when a normal click fires, a and b are undefined
370 * // for a trigger like below a refers too "foo" and b refers to "bar"
371 * }).trigger("click", ["foo", "bar"]);
372 * @desc Example of how to pass arbitrary data to an event
374 * @example $("p").bind("myEvent",function(event,message1,message2) {
375 * alert(message1 + ' ' + message2);
377 * $("p").trigger("myEvent",["Hello","World"]);
378 * @result alert('Hello World') // One for each paragraph
382 * @param String type An event type to trigger.
383 * @param Array data (optional) Additional data to pass as arguments (after the event object) to the event handler
386 trigger: function( type, data ) {
387 return this.each(function(){
388 jQuery.event.trigger( type, data, this );
393 * Toggle between two function calls every other click.
394 * Whenever a matched element is clicked, the first specified function
395 * is fired, when clicked again, the second is fired. All subsequent
396 * clicks continue to rotate through the two functions.
398 * Use unbind("click") to remove.
400 * @example $("p").toggle(function(){
401 * $(this).addClass("selected");
403 * $(this).removeClass("selected");
408 * @param Function even The function to execute on every even click.
409 * @param Function odd The function to execute on every odd click.
413 // Save reference to arguments for access in closure
416 return this.click(function(e) {
417 // Figure out which function to execute
418 this.lastToggle = this.lastToggle == 0 ? 1 : 0;
420 // Make sure that clicks stop
423 // and execute the function
424 return a[this.lastToggle].apply( this, [e] ) || false;
429 * A method for simulating hovering (moving the mouse on, and off,
430 * an object). This is a custom method which provides an 'in' to a
433 * Whenever the mouse cursor is moved over a matched
434 * element, the first specified function is fired. Whenever the mouse
435 * moves off of the element, the second specified function fires.
436 * Additionally, checks are in place to see if the mouse is still within
437 * the specified element itself (for example, an image inside of a div),
438 * and if it is, it will continue to 'hover', and not move out
439 * (a common error in using a mouseout event handler).
441 * @example $("p").hover(function(){
442 * $(this).addClass("hover");
444 * $(this).removeClass("hover");
449 * @param Function over The function to fire whenever the mouse is moved over a matched element.
450 * @param Function out The function to fire whenever the mouse is moved off of a matched element.
453 hover: function(f,g) {
455 // A private function for handling mouse 'hovering'
456 function handleHover(e) {
457 // Check if mouse(over|out) are still within the same parent element
458 var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
460 // Traverse up the tree
461 while ( p && p != this ) try { p = p.parentNode } catch(e) { p = this; };
463 // If we actually just moused on to a sub-element, ignore it
464 if ( p == this ) return false;
466 // Execute the right function
467 return (e.type == "mouseover" ? f : g).apply(this, [e]);
470 // Bind the function to the two event listeners
471 return this.mouseover(handleHover).mouseout(handleHover);
475 * Bind a function to be executed whenever the DOM is ready to be
476 * traversed and manipulated. This is probably the most important
477 * function included in the event module, as it can greatly improve
478 * the response times of your web applications.
480 * In a nutshell, this is a solid replacement for using window.onload,
481 * and attaching a function to that. By using this method, your bound function
482 * will be called the instant the DOM is ready to be read and manipulated,
483 * which is when what 99.99% of all JavaScript code needs to run.
485 * There is one argument passed to the ready event handler: A reference to
486 * the jQuery function. You can name that argument whatever you like, and
487 * can therefore stick with the $ alias without risk of naming collisions.
489 * Please ensure you have no code in your <body> onload event handler,
490 * otherwise $(document).ready() may not fire.
492 * You can have as many $(document).ready events on your page as you like.
493 * The functions are then executed in the order they were added.
495 * @example $(document).ready(function(){ Your code here... });
497 * @example jQuery(function($) {
498 * // Your code using failsafe $ alias here...
500 * @desc Uses both the [[Core#.24.28_fn_.29|shortcut]] for $(document).ready() and the argument
501 * to write failsafe jQuery code using the $ alias, without relying on the
506 * @param Function fn The function to be executed when the DOM is ready.
508 * @see $.noConflict()
512 // If the DOM is already ready
513 if ( jQuery.isReady )
514 // Execute the function immediately
515 f.apply( document, [jQuery] );
517 // Otherwise, remember the function for later
519 // Add the function to the wait list
520 jQuery.readyList.push( function() { return f.apply(this, [jQuery]) } );
529 * All the code that makes DOM Ready work nicely.
534 // Handle when the DOM is ready
536 // Make sure that the DOM is not already loaded
537 if ( !jQuery.isReady ) {
538 // Remember that the DOM is ready
539 jQuery.isReady = true;
541 // If there are functions bound, to execute
542 if ( jQuery.readyList ) {
543 // Execute all of them
544 jQuery.each( jQuery.readyList, function(){
545 this.apply( document );
548 // Reset the list of functions
549 jQuery.readyList = null;
551 // Remove event lisenter to avoid memory leak
552 if ( jQuery.browser.mozilla || jQuery.browser.opera )
553 document.removeEventListener( "DOMContentLoaded", jQuery.ready, false );
561 * Bind a function to the scroll event of each matched element.
563 * @example $("p").scroll( function() { alert("Hello"); } );
564 * @before <p>Hello</p>
565 * @result <p onscroll="alert('Hello');">Hello</p>
569 * @param Function fn A function to bind to the scroll event on each of the matched elements.
574 * Bind a function to the submit event of each matched element.
576 * @example $("#myform").submit( function() {
577 * return $("input", this).val().length > 0;
579 * @before <form id="myform"><input /></form>
580 * @desc Prevents the form submission when the input has no value entered.
584 * @param Function fn A function to bind to the submit event on each of the matched elements.
589 * Trigger the submit event of each matched element. This causes all of the functions
590 * that have been bound to that submit event to be executed, and calls the browser's
591 * default submit action on the matching element(s). This default action can be prevented
592 * by returning false from one of the functions bound to the submit event.
594 * Note: This does not execute the submit method of the form element! If you need to
595 * submit the form via code, you have to use the DOM method, eg. $("form")[0].submit();
597 * @example $("form").submit();
598 * @desc Triggers all submit events registered to the matched form(s), and submits them.
606 * Bind a function to the focus event of each matched element.
608 * @example $("p").focus( function() { alert("Hello"); } );
609 * @before <p>Hello</p>
610 * @result <p onfocus="alert('Hello');">Hello</p>
614 * @param Function fn A function to bind to the focus event on each of the matched elements.
619 * Trigger the focus event of each matched element. This causes all of the functions
620 * that have been bound to thet focus event to be executed.
622 * Note: This does not execute the focus method of the underlying elements! If you need to
623 * focus an element via code, you have to use the DOM method, eg. $("#myinput")[0].focus();
625 * @example $("p").focus();
626 * @before <p onfocus="alert('Hello');">Hello</p>
627 * @result alert('Hello');
635 * Bind a function to the keydown event of each matched element.
637 * @example $("p").keydown( function() { alert("Hello"); } );
638 * @before <p>Hello</p>
639 * @result <p onkeydown="alert('Hello');">Hello</p>
643 * @param Function fn A function to bind to the keydown event on each of the matched elements.
648 * Bind a function to the dblclick event of each matched element.
650 * @example $("p").dblclick( function() { alert("Hello"); } );
651 * @before <p>Hello</p>
652 * @result <p ondblclick="alert('Hello');">Hello</p>
656 * @param Function fn A function to bind to the dblclick event on each of the matched elements.
661 * Bind a function to the keypress event of each matched element.
663 * @example $("p").keypress( function() { alert("Hello"); } );
664 * @before <p>Hello</p>
665 * @result <p onkeypress="alert('Hello');">Hello</p>
669 * @param Function fn A function to bind to the keypress event on each of the matched elements.
674 * Bind a function to the error event of each matched element.
676 * @example $("p").error( function() { alert("Hello"); } );
677 * @before <p>Hello</p>
678 * @result <p onerror="alert('Hello');">Hello</p>
682 * @param Function fn A function to bind to the error event on each of the matched elements.
687 * Bind a function to the blur event of each matched element.
689 * @example $("p").blur( function() { alert("Hello"); } );
690 * @before <p>Hello</p>
691 * @result <p onblur="alert('Hello');">Hello</p>
695 * @param Function fn A function to bind to the blur event on each of the matched elements.
700 * Trigger the blur event of each matched element. This causes all of the functions
701 * that have been bound to that blur event to be executed, and calls the browser's
702 * default blur action on the matching element(s). This default action can be prevented
703 * by returning false from one of the functions bound to the blur event.
705 * Note: This does not execute the blur method of the underlying elements! If you need to
706 * blur an element via code, you have to use the DOM method, eg. $("#myinput")[0].blur();
708 * @example $("p").blur();
709 * @before <p onblur="alert('Hello');">Hello</p>
710 * @result alert('Hello');
718 * Bind a function to the load event of each matched element.
720 * @example $("p").load( function() { alert("Hello"); } );
721 * @before <p>Hello</p>
722 * @result <p onload="alert('Hello');">Hello</p>
726 * @param Function fn A function to bind to the load event on each of the matched elements.
731 * Bind a function to the select event of each matched element.
733 * @example $("p").select( function() { alert("Hello"); } );
734 * @before <p>Hello</p>
735 * @result <p onselect="alert('Hello');">Hello</p>
739 * @param Function fn A function to bind to the select event on each of the matched elements.
744 * Trigger the select event of each matched element. This causes all of the functions
745 * that have been bound to that select event to be executed, and calls the browser's
746 * default select action on the matching element(s). This default action can be prevented
747 * by returning false from one of the functions bound to the select event.
749 * @example $("p").select();
750 * @before <p onselect="alert('Hello');">Hello</p>
751 * @result alert('Hello');
759 * Bind a function to the mouseup event of each matched element.
761 * @example $("p").mouseup( function() { alert("Hello"); } );
762 * @before <p>Hello</p>
763 * @result <p onmouseup="alert('Hello');">Hello</p>
767 * @param Function fn A function to bind to the mouseup event on each of the matched elements.
772 * Bind a function to the unload event of each matched element.
774 * @example $("p").unload( function() { alert("Hello"); } );
775 * @before <p>Hello</p>
776 * @result <p onunload="alert('Hello');">Hello</p>
780 * @param Function fn A function to bind to the unload event on each of the matched elements.
785 * Bind a function to the change event of each matched element.
787 * @example $("p").change( function() { alert("Hello"); } );
788 * @before <p>Hello</p>
789 * @result <p onchange="alert('Hello');">Hello</p>
793 * @param Function fn A function to bind to the change event on each of the matched elements.
798 * Bind a function to the mouseout event of each matched element.
800 * @example $("p").mouseout( function() { alert("Hello"); } );
801 * @before <p>Hello</p>
802 * @result <p onmouseout="alert('Hello');">Hello</p>
806 * @param Function fn A function to bind to the mouseout event on each of the matched elements.
811 * Bind a function to the keyup event of each matched element.
813 * @example $("p").keyup( function() { alert("Hello"); } );
814 * @before <p>Hello</p>
815 * @result <p onkeyup="alert('Hello');">Hello</p>
819 * @param Function fn A function to bind to the keyup event on each of the matched elements.
824 * Bind a function to the click event of each matched element.
826 * @example $("p").click( function() { alert("Hello"); } );
827 * @before <p>Hello</p>
828 * @result <p onclick="alert('Hello');">Hello</p>
832 * @param Function fn A function to bind to the click event on each of the matched elements.
837 * Trigger the click event of each matched element. This causes all of the functions
838 * that have been bound to thet click event to be executed.
840 * @example $("p").click();
841 * @before <p onclick="alert('Hello');">Hello</p>
842 * @result alert('Hello');
850 * Bind a function to the resize event of each matched element.
852 * @example $("p").resize( function() { alert("Hello"); } );
853 * @before <p>Hello</p>
854 * @result <p onresize="alert('Hello');">Hello</p>
858 * @param Function fn A function to bind to the resize event on each of the matched elements.
863 * Bind a function to the mousemove event of each matched element.
865 * @example $("p").mousemove( function() { alert("Hello"); } );
866 * @before <p>Hello</p>
867 * @result <p onmousemove="alert('Hello');">Hello</p>
871 * @param Function fn A function to bind to the mousemove event on each of the matched elements.
876 * Bind a function to the mousedown event of each matched element.
878 * @example $("p").mousedown( function() { alert("Hello"); } );
879 * @before <p>Hello</p>
880 * @result <p onmousedown="alert('Hello');">Hello</p>
884 * @param Function fn A function to bind to the mousedown event on each of the matched elements.
889 * Bind a function to the mouseover event of each matched element.
891 * @example $("p").mouseover( function() { alert("Hello"); } );
892 * @before <p>Hello</p>
893 * @result <p onmouseover="alert('Hello');">Hello</p>
897 * @param Function fn A function to bind to the mousedown event on each of the matched elements.
900 jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
901 "mousedown,mouseup,mousemove,mouseover,mouseout,change,select," +
902 "submit,keydown,keypress,keyup,error").split(","), function(i,o){
904 // Handle event binding
905 jQuery.fn[o] = function(f){
906 return f ? this.bind(o, f) : this.trigger(o);
911 // If Mozilla is used
912 if ( jQuery.browser.mozilla || jQuery.browser.opera )
913 // Use the handy event callback
914 document.addEventListener( "DOMContentLoaded", jQuery.ready, false );
916 // If IE is used, use the excellent hack by Matthias Miller
917 // http://www.outofhanwell.com/blog/index.php?title=the_window_onload_problem_revisited
918 else if ( jQuery.browser.msie ) {
920 // Only works if you document.write() it
921 document.write("<scr" + "ipt id=__ie_init defer=true " +
922 "src=//:><\/script>");
924 // Use the defer script hack
925 var script = document.getElementById("__ie_init");
927 // script does not exist if jQuery is loaded dynamically
929 script.onreadystatechange = function() {
930 if ( this.readyState != "complete" ) return;
931 this.parentNode.removeChild( this );
939 } else if ( jQuery.browser.safari )
940 // Continually check to see if the document.readyState is valid
941 jQuery.safariTimer = setInterval(function(){
942 // loaded and complete are both valid states
943 if ( document.readyState == "loaded" ||
944 document.readyState == "complete" ) {
946 // If either one are found, remove the timer
947 clearInterval( jQuery.safariTimer );
948 jQuery.safariTimer = null;
950 // and execute any waiting functions
955 // A fallback to window.onload, that will always work
956 jQuery.event.add( window, "load", jQuery.ready );
960 // Clean up after IE to avoid memory leaks
961 if (jQuery.browser.msie)
962 jQuery(window).one("unload", function() {
963 var global = jQuery.event.global;
964 for ( var type in global ) {
965 var els = global[type], i = els.length;
966 if ( i && type != 'unload' )
968 jQuery.event.remove(els[i-1], type);