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 // Make sure that the function being executed has a unique ID
18 handler.guid = this.guid++;
20 // if data is passed, bind to handler
21 if( data != undefined ) {
22 // Create temporary function pointer to original handler
25 // Create unique handler function, wrapped around original handler
26 handler = function() {
27 // Pass arguments and context to original handler
28 return fn.apply(this, arguments);
31 // Store data in unique handler
34 // Set the guid of unique handler to the same of original handler, so it can be removed
35 handler.guid = fn.guid;
38 // Init the element's event structure
43 element.$handle = function() {
44 jQuery.event.handle.apply(element, arguments);
47 // Get the current list of functions bound to this event
48 var handlers = element.$events[type];
50 // Init the event handler queue
52 handlers = element.$events[type] = {};
54 // And bind the global event handler to the element
55 if (element.addEventListener)
56 element.addEventListener(type, element.$handle, false);
57 else if (element.attachEvent)
58 element.attachEvent("on" + type, element.$handle);
61 // Add the function to the element's handler list
62 handlers[handler.guid] = handler;
64 // Remember the function in a global list (for triggering)
65 if (!this.global[type])
66 this.global[type] = [];
67 this.global[type].push( element );
73 // Detach an event or set of events from an element
74 remove: function(element, type, handler) {
75 var events = element.$events, ret;
78 // type is actually an event object here
79 if ( type && type.type ) {
80 handler = type.handler;
85 for ( type in events )
86 this.remove( element, type );
88 } else if ( events[type] ) {
89 // remove the given handler for the given type
91 delete events[type][handler.guid];
93 // remove all handlers for the given type
95 for ( handler in element.$events[type] )
96 delete events[type][handler];
98 // remove generic event handler if no more handlers exist
99 for ( ret in events[type] ) break;
101 if (element.removeEventListener)
102 element.removeEventListener(type, element.$handle, false);
103 else if (element.detachEvent)
104 element.detachEvent("on" + type, element.$handle);
110 // Remove the expando if it's no longer used
111 for ( ret in events ) break;
113 element.$handle = element.$events = null;
117 trigger: function(type, data, element) {
118 // Clone the incoming data, if any
119 data = jQuery.makeArray(data || []);
121 // Handle a global trigger
123 jQuery.each( this.global[type] || [], function(){
124 jQuery.event.trigger( type, data, this );
127 // Handle triggering a single element
129 var val, ret, fn = jQuery.isFunction( element[ type ] || null );
131 // Pass along a fake event
132 data.unshift( this.fix({ type: type, target: element }) );
135 if ( (val = this.handle.apply( element, data )) !== false )
136 this.triggered = true;
138 if ( fn && val !== false && !jQuery.nodeName(element, 'a') )
141 this.triggered = false;
145 handle: function(event) {
146 // returned undefined or false
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 )
154 // Empty object is for triggered events with no data
155 event = jQuery.event.fix( event || window.event || {} );
157 var c = this.$events && this.$events[event.type], args = [].slice.call( arguments, 1 );
158 args.unshift( event );
161 // Pass in a reference to the handler function itself
162 // So that we can later remove it
163 args[0].handler = c[j];
164 args[0].data = c[j].data;
166 if ( c[j].apply( this, args ) === false ) {
167 event.preventDefault();
168 event.stopPropagation();
173 // Clean up added properties in IE to prevent memory leak
174 if (jQuery.browser.msie)
175 event.target = event.preventDefault = event.stopPropagation =
176 event.handler = event.data = null;
181 fix: function(event) {
182 // store a copy of the original event object
183 // and clone to set read-only properties
184 var originalEvent = event;
185 event = jQuery.extend({}, originalEvent);
187 // add preventDefault and stopPropagation since
188 // they will not work on the clone
189 event.preventDefault = function() {
190 // if preventDefault exists run it on the original event
191 if (originalEvent.preventDefault)
192 return originalEvent.preventDefault();
193 // otherwise set the returnValue property of the original event to false (IE)
194 originalEvent.returnValue = false;
196 event.stopPropagation = function() {
197 // if stopPropagation exists run it on the original event
198 if (originalEvent.stopPropagation)
199 return originalEvent.stopPropagation();
200 // otherwise set the cancelBubble property of the original event to true (IE)
201 originalEvent.cancelBubble = true;
204 // Fix target property, if necessary
205 if ( !event.target && event.srcElement )
206 event.target = event.srcElement;
208 // check if target is a textnode (safari)
209 if (jQuery.browser.safari && event.target.nodeType == 3)
210 event.target = originalEvent.target.parentNode;
212 // Add relatedTarget, if necessary
213 if ( !event.relatedTarget && event.fromElement )
214 event.relatedTarget = event.fromElement == event.target ? event.toElement : event.fromElement;
216 // Calculate pageX/Y if missing and clientX/Y available
217 if ( event.pageX == null && event.clientX != null ) {
218 var e = document.documentElement || document.body;
219 event.pageX = event.clientX + e.scrollLeft;
220 event.pageY = event.clientY + e.scrollTop;
223 // Add which for key events
224 if ( !event.which && (event.charCode || event.keyCode) )
225 event.which = event.charCode || event.keyCode;
227 // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
228 if ( !event.metaKey && event.ctrlKey )
229 event.metaKey = event.ctrlKey;
231 // Add which for click: 1 == left; 2 == middle; 3 == right
232 // Note: button is not normalized, so don't use it
233 if ( !event.which && event.button )
234 event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
243 * Binds a handler to a particular event (like click) for each matched element.
244 * The event handler is passed an event object that you can use to prevent
245 * default behaviour. To stop both default action and event bubbling, your handler
246 * has to return false.
248 * In most cases, you can define your event handlers as anonymous functions
249 * (see first example). In cases where that is not possible, you can pass additional
250 * data as the second parameter (and the handler function as the third), see
253 * @example $("p").bind("click", function(){
254 * alert( $(this).text() );
256 * @before <p>Hello</p>
257 * @result alert("Hello")
259 * @example function handler(event) {
260 * alert(event.data.foo);
262 * $("p").bind("click", {foo: "bar"}, handler)
263 * @result alert("bar")
264 * @desc Pass some additional data to the event handler.
266 * @example $("form").bind("submit", function() { return false; })
267 * @desc Cancel a default action and prevent it from bubbling by returning false
268 * from your function.
270 * @example $("form").bind("submit", function(event){
271 * event.preventDefault();
273 * @desc Cancel only the default action by using the preventDefault method.
276 * @example $("form").bind("submit", function(event){
277 * event.stopPropagation();
279 * @desc Stop only an event from bubbling by using the stopPropagation method.
283 * @param String type An event type
284 * @param Object data (optional) Additional data passed to the event handler as event.data
285 * @param Function fn A function to bind to the event on each of the set of matched elements
288 bind: function( type, data, fn ) {
289 return this.each(function(){
290 jQuery.event.add( this, type, fn || data, fn && data );
295 * Binds a handler to a particular event (like click) for each matched element.
296 * The handler is executed only once for each element. Otherwise, the same rules
297 * as described in bind() apply.
298 * The event handler is passed an event object that you can use to prevent
299 * default behaviour. To stop both default action and event bubbling, your handler
300 * has to return false.
302 * In most cases, you can define your event handlers as anonymous functions
303 * (see first example). In cases where that is not possible, you can pass additional
304 * data as the second paramter (and the handler function as the third), see
307 * @example $("p").one("click", function(){
308 * alert( $(this).text() );
310 * @before <p>Hello</p>
311 * @result alert("Hello")
315 * @param String type An event type
316 * @param Object data (optional) Additional data passed to the event handler as event.data
317 * @param Function fn A function to bind to the event on each of the set of matched elements
320 one: function( type, data, fn ) {
321 return this.each(function(){
322 jQuery.event.add( this, type, function(event) {
323 jQuery(this).unbind(event);
324 return (fn || data).apply( this, arguments);
330 * The opposite of bind, removes a bound event from each of the matched
333 * Without any arguments, all bound events are removed.
335 * If the type is provided, all bound events of that type are removed.
337 * If the function that was passed to bind is provided as the second argument,
338 * only that specific event handler is removed.
340 * @example $("p").unbind()
341 * @before <p onclick="alert('Hello');">Hello</p>
342 * @result [ <p>Hello</p> ]
344 * @example $("p").unbind( "click" )
345 * @before <p onclick="alert('Hello');">Hello</p>
346 * @result [ <p>Hello</p> ]
348 * @example $("p").unbind( "click", function() { alert("Hello"); } )
349 * @before <p onclick="alert('Hello');">Hello</p>
350 * @result [ <p>Hello</p> ]
354 * @param String type (optional) An event type
355 * @param Function fn (optional) A function to unbind from the event on each of the set of matched elements
358 unbind: function( type, fn ) {
359 return this.each(function(){
360 jQuery.event.remove( this, type, fn );
365 * Trigger a type of event on every matched element. This will also cause
366 * the default action of the browser with the same name (if one exists)
367 * to be executed. For example, passing 'submit' to the trigger()
368 * function will also cause the browser to submit the form. This
369 * default action can be prevented by returning false from one of
370 * the functions bound to the event.
372 * You can also trigger custom events registered with bind.
374 * @example $("p").trigger("click")
375 * @before <p click="alert('hello')">Hello</p>
376 * @result alert('hello')
378 * @example $("p").click(function(event, a, b) {
379 * // when a normal click fires, a and b are undefined
380 * // for a trigger like below a refers too "foo" and b refers to "bar"
381 * }).trigger("click", ["foo", "bar"]);
382 * @desc Example of how to pass arbitrary data to an event
384 * @example $("p").bind("myEvent",function(event,message1,message2) {
385 * alert(message1 + ' ' + message2);
387 * $("p").trigger("myEvent",["Hello","World"]);
388 * @result alert('Hello World') // One for each paragraph
392 * @param String type An event type to trigger.
393 * @param Array data (optional) Additional data to pass as arguments (after the event object) to the event handler
396 trigger: function( type, data ) {
397 return this.each(function(){
398 jQuery.event.trigger( type, data, this );
403 * Toggle between two function calls every other click.
404 * Whenever a matched element is clicked, the first specified function
405 * is fired, when clicked again, the second is fired. All subsequent
406 * clicks continue to rotate through the two functions.
408 * Use unbind("click") to remove.
410 * @example $("p").toggle(function(){
411 * $(this).addClass("selected");
413 * $(this).removeClass("selected");
418 * @param Function even The function to execute on every even click.
419 * @param Function odd The function to execute on every odd click.
423 // Save reference to arguments for access in closure
426 return this.click(function(e) {
427 // Figure out which function to execute
428 this.lastToggle = 0 == this.lastToggle ? 1 : 0;
430 // Make sure that clicks stop
433 // and execute the function
434 return a[this.lastToggle].apply( this, [e] ) || false;
439 * A method for simulating hovering (moving the mouse on, and off,
440 * an object). This is a custom method which provides an 'in' to a
443 * Whenever the mouse cursor is moved over a matched
444 * element, the first specified function is fired. Whenever the mouse
445 * moves off of the element, the second specified function fires.
446 * Additionally, checks are in place to see if the mouse is still within
447 * the specified element itself (for example, an image inside of a div),
448 * and if it is, it will continue to 'hover', and not move out
449 * (a common error in using a mouseout event handler).
451 * @example $("p").hover(function(){
452 * $(this).addClass("hover");
454 * $(this).removeClass("hover");
459 * @param Function over The function to fire whenever the mouse is moved over a matched element.
460 * @param Function out The function to fire whenever the mouse is moved off of a matched element.
463 hover: function(f,g) {
465 // A private function for handling mouse 'hovering'
466 function handleHover(e) {
467 // Check if mouse(over|out) are still within the same parent element
468 var p = e.relatedTarget;
470 // Traverse up the tree
471 while ( p && p != this ) try { p = p.parentNode } catch(e) { p = this; };
473 // If we actually just moused on to a sub-element, ignore it
474 if ( p == this ) return false;
476 // Execute the right function
477 return (e.type == "mouseover" ? f : g).apply(this, [e]);
480 // Bind the function to the two event listeners
481 return this.mouseover(handleHover).mouseout(handleHover);
485 * Bind a function to be executed whenever the DOM is ready to be
486 * traversed and manipulated. This is probably the most important
487 * function included in the event module, as it can greatly improve
488 * the response times of your web applications.
490 * In a nutshell, this is a solid replacement for using window.onload,
491 * and attaching a function to that. By using this method, your bound function
492 * will be called the instant the DOM is ready to be read and manipulated,
493 * which is when what 99.99% of all JavaScript code needs to run.
495 * There is one argument passed to the ready event handler: A reference to
496 * the jQuery function. You can name that argument whatever you like, and
497 * can therefore stick with the $ alias without risk of naming collisions.
499 * Please ensure you have no code in your <body> onload event handler,
500 * otherwise $(document).ready() may not fire.
502 * You can have as many $(document).ready events on your page as you like.
503 * The functions are then executed in the order they were added.
505 * @example $(document).ready(function(){ Your code here... });
507 * @example jQuery(function($) {
508 * // Your code using failsafe $ alias here...
510 * @desc Uses both the [[Core#.24.28_fn_.29|shortcut]] for $(document).ready() and the argument
511 * to write failsafe jQuery code using the $ alias, without relying on the
516 * @param Function fn The function to be executed when the DOM is ready.
518 * @see $.noConflict()
522 // If the DOM is already ready
523 if ( jQuery.isReady )
524 // Execute the function immediately
525 f.apply( document, [jQuery] );
527 // Otherwise, remember the function for later
529 // Add the function to the wait list
530 jQuery.readyList.push( function() { return f.apply(this, [jQuery]) } );
539 * All the code that makes DOM Ready work nicely.
544 // Handle when the DOM is ready
546 // Make sure that the DOM is not already loaded
547 if ( !jQuery.isReady ) {
548 // Remember that the DOM is ready
549 jQuery.isReady = true;
551 // If there are functions bound, to execute
552 if ( jQuery.readyList ) {
553 // Execute all of them
554 jQuery.each( jQuery.readyList, function(){
555 this.apply( document );
558 // Reset the list of functions
559 jQuery.readyList = null;
561 // Remove event listener to avoid memory leak
562 if ( jQuery.browser.mozilla || jQuery.browser.opera )
563 document.removeEventListener( "DOMContentLoaded", jQuery.ready, false );
565 // Remove script element used by IE hack
566 jQuery(window).load(function(){ jQuery("#__ie_init").remove(); });
574 * Bind a function to the scroll event of each matched element.
576 * @example $("p").scroll( function() { alert("Hello"); } );
577 * @before <p>Hello</p>
578 * @result <p onscroll="alert('Hello');">Hello</p>
582 * @param Function fn A function to bind to the scroll event on each of the matched elements.
587 * Bind a function to the submit event of each matched element.
589 * @example $("#myform").submit( function() {
590 * return $("input", this).val().length > 0;
592 * @before <form id="myform"><input /></form>
593 * @desc Prevents the form submission when the input has no value entered.
597 * @param Function fn A function to bind to the submit event on each of the matched elements.
602 * Trigger the submit event of each matched element. This causes all of the functions
603 * that have been bound to that submit event to be executed, and calls the browser's
604 * default submit action on the matching element(s). This default action can be prevented
605 * by returning false from one of the functions bound to the submit event.
607 * Note: This does not execute the submit method of the form element! If you need to
608 * submit the form via code, you have to use the DOM method, eg. $("form")[0].submit();
610 * @example $("form").submit();
611 * @desc Triggers all submit events registered to the matched form(s), and submits them.
619 * Bind a function to the focus event of each matched element.
621 * @example $("p").focus( function() { alert("Hello"); } );
622 * @before <p>Hello</p>
623 * @result <p onfocus="alert('Hello');">Hello</p>
627 * @param Function fn A function to bind to the focus event on each of the matched elements.
632 * Trigger the focus event of each matched element. This causes all of the functions
633 * that have been bound to thet focus event to be executed.
635 * Note: This does not execute the focus method of the underlying elements! If you need to
636 * focus an element via code, you have to use the DOM method, eg. $("#myinput")[0].focus();
638 * @example $("p").focus();
639 * @before <p onfocus="alert('Hello');">Hello</p>
640 * @result alert('Hello');
648 * Bind a function to the keydown event of each matched element.
650 * @example $("p").keydown( function() { alert("Hello"); } );
651 * @before <p>Hello</p>
652 * @result <p onkeydown="alert('Hello');">Hello</p>
656 * @param Function fn A function to bind to the keydown event on each of the matched elements.
661 * Bind a function to the dblclick event of each matched element.
663 * @example $("p").dblclick( function() { alert("Hello"); } );
664 * @before <p>Hello</p>
665 * @result <p ondblclick="alert('Hello');">Hello</p>
669 * @param Function fn A function to bind to the dblclick event on each of the matched elements.
674 * Bind a function to the keypress event of each matched element.
676 * @example $("p").keypress( function() { alert("Hello"); } );
677 * @before <p>Hello</p>
678 * @result <p onkeypress="alert('Hello');">Hello</p>
682 * @param Function fn A function to bind to the keypress event on each of the matched elements.
687 * Bind a function to the error event of each matched element.
689 * @example $("p").error( function() { alert("Hello"); } );
690 * @before <p>Hello</p>
691 * @result <p onerror="alert('Hello');">Hello</p>
695 * @param Function fn A function to bind to the error event on each of the matched elements.
700 * Bind a function to the blur event of each matched element.
702 * @example $("p").blur( function() { alert("Hello"); } );
703 * @before <p>Hello</p>
704 * @result <p onblur="alert('Hello');">Hello</p>
708 * @param Function fn A function to bind to the blur event on each of the matched elements.
713 * Trigger the blur event of each matched element. This causes all of the functions
714 * that have been bound to that blur event to be executed, and calls the browser's
715 * default blur action on the matching element(s). This default action can be prevented
716 * by returning false from one of the functions bound to the blur event.
718 * Note: This does not execute the blur method of the underlying elements! If you need to
719 * blur an element via code, you have to use the DOM method, eg. $("#myinput")[0].blur();
721 * @example $("p").blur();
722 * @before <p onblur="alert('Hello');">Hello</p>
723 * @result alert('Hello');
731 * Bind a function to the load event of each matched element.
733 * @example $("p").load( function() { alert("Hello"); } );
734 * @before <p>Hello</p>
735 * @result <p onload="alert('Hello');">Hello</p>
739 * @param Function fn A function to bind to the load event on each of the matched elements.
744 * Bind a function to the select event of each matched element.
746 * @example $("p").select( function() { alert("Hello"); } );
747 * @before <p>Hello</p>
748 * @result <p onselect="alert('Hello');">Hello</p>
752 * @param Function fn A function to bind to the select event on each of the matched elements.
757 * Trigger the select event of each matched element. This causes all of the functions
758 * that have been bound to that select event to be executed, and calls the browser's
759 * default select action on the matching element(s). This default action can be prevented
760 * by returning false from one of the functions bound to the select event.
762 * @example $("p").select();
763 * @before <p onselect="alert('Hello');">Hello</p>
764 * @result alert('Hello');
772 * Bind a function to the mouseup event of each matched element.
774 * @example $("p").mouseup( function() { alert("Hello"); } );
775 * @before <p>Hello</p>
776 * @result <p onmouseup="alert('Hello');">Hello</p>
780 * @param Function fn A function to bind to the mouseup event on each of the matched elements.
785 * Bind a function to the unload event of each matched element.
787 * @example $("p").unload( function() { alert("Hello"); } );
788 * @before <p>Hello</p>
789 * @result <p onunload="alert('Hello');">Hello</p>
793 * @param Function fn A function to bind to the unload event on each of the matched elements.
798 * Bind a function to the change event of each matched element.
800 * @example $("p").change( function() { alert("Hello"); } );
801 * @before <p>Hello</p>
802 * @result <p onchange="alert('Hello');">Hello</p>
806 * @param Function fn A function to bind to the change event on each of the matched elements.
811 * Bind a function to the mouseout event of each matched element.
813 * @example $("p").mouseout( function() { alert("Hello"); } );
814 * @before <p>Hello</p>
815 * @result <p onmouseout="alert('Hello');">Hello</p>
819 * @param Function fn A function to bind to the mouseout event on each of the matched elements.
824 * Bind a function to the keyup event of each matched element.
826 * @example $("p").keyup( function() { alert("Hello"); } );
827 * @before <p>Hello</p>
828 * @result <p onkeyup="alert('Hello');">Hello</p>
832 * @param Function fn A function to bind to the keyup event on each of the matched elements.
837 * Bind a function to the click event of each matched element.
839 * @example $("p").click( function() { alert("Hello"); } );
840 * @before <p>Hello</p>
841 * @result <p onclick="alert('Hello');">Hello</p>
845 * @param Function fn A function to bind to the click event on each of the matched elements.
850 * Trigger the click event of each matched element. This causes all of the functions
851 * that have been bound to thet click event to be executed.
853 * @example $("p").click();
854 * @before <p onclick="alert('Hello');">Hello</p>
855 * @result alert('Hello');
863 * Bind a function to the resize event of each matched element.
865 * @example $("p").resize( function() { alert("Hello"); } );
866 * @before <p>Hello</p>
867 * @result <p onresize="alert('Hello');">Hello</p>
871 * @param Function fn A function to bind to the resize event on each of the matched elements.
876 * Bind a function to the mousemove event of each matched element.
878 * @example $("p").mousemove( function() { alert("Hello"); } );
879 * @before <p>Hello</p>
880 * @result <p onmousemove="alert('Hello');">Hello</p>
884 * @param Function fn A function to bind to the mousemove event on each of the matched elements.
889 * Bind a function to the mousedown event of each matched element.
891 * @example $("p").mousedown( function() { alert("Hello"); } );
892 * @before <p>Hello</p>
893 * @result <p onmousedown="alert('Hello');">Hello</p>
897 * @param Function fn A function to bind to the mousedown event on each of the matched elements.
902 * Bind a function to the mouseover event of each matched element.
904 * @example $("p").mouseover( function() { alert("Hello"); } );
905 * @before <p>Hello</p>
906 * @result <p onmouseover="alert('Hello');">Hello</p>
910 * @param Function fn A function to bind to the mousedown event on each of the matched elements.
913 jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
914 "mousedown,mouseup,mousemove,mouseover,mouseout,change,select," +
915 "submit,keydown,keypress,keyup,error").split(","), function(i,o){
917 // Handle event binding
918 jQuery.fn[o] = function(f){
919 return f ? this.bind(o, f) : this.trigger(o);
924 // If Mozilla is used
925 if ( jQuery.browser.mozilla || jQuery.browser.opera )
926 // Use the handy event callback
927 document.addEventListener( "DOMContentLoaded", jQuery.ready, false );
929 // If IE is used, use the excellent hack by Matthias Miller
930 // http://www.outofhanwell.com/blog/index.php?title=the_window_onload_problem_revisited
931 else if ( jQuery.browser.msie ) {
933 // Only works if you document.write() it
934 document.write("<scr" + "ipt id=__ie_init defer=true " +
935 "src=//:><\/script>");
937 // Use the defer script hack
938 var script = document.getElementById("__ie_init");
940 // script does not exist if jQuery is loaded dynamically
942 script.onreadystatechange = function() {
943 if ( this.readyState != "complete" ) return;
951 } else if ( jQuery.browser.safari )
952 // Continually check to see if the document.readyState is valid
953 jQuery.safariTimer = setInterval(function(){
954 // loaded and complete are both valid states
955 if ( document.readyState == "loaded" ||
956 document.readyState == "complete" ) {
958 // If either one are found, remove the timer
959 clearInterval( jQuery.safariTimer );
960 jQuery.safariTimer = null;
962 // and execute any waiting functions
967 // A fallback to window.onload, that will always work
968 jQuery.event.add( window, "load", jQuery.ready );
972 // Clean up after IE to avoid memory leaks
973 if (jQuery.browser.msie)
974 jQuery(window).one("unload", function() {
975 var global = jQuery.event.global;
976 for ( var type in global ) {
977 var els = global[type], i = els.length;
978 if ( i && type != 'unload' )
980 jQuery.event.remove(els[i-1], type);