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 );
555 // Remove script element used by IE hack
556 jQuery(window).load(function(){ jQuery("#__ie_init").remove(); });
564 * Bind a function to the scroll event of each matched element.
566 * @example $("p").scroll( function() { alert("Hello"); } );
567 * @before <p>Hello</p>
568 * @result <p onscroll="alert('Hello');">Hello</p>
572 * @param Function fn A function to bind to the scroll event on each of the matched elements.
577 * Bind a function to the submit event of each matched element.
579 * @example $("#myform").submit( function() {
580 * return $("input", this).val().length > 0;
582 * @before <form id="myform"><input /></form>
583 * @desc Prevents the form submission when the input has no value entered.
587 * @param Function fn A function to bind to the submit event on each of the matched elements.
592 * Trigger the submit event of each matched element. This causes all of the functions
593 * that have been bound to that submit event to be executed, and calls the browser's
594 * default submit action on the matching element(s). This default action can be prevented
595 * by returning false from one of the functions bound to the submit event.
597 * Note: This does not execute the submit method of the form element! If you need to
598 * submit the form via code, you have to use the DOM method, eg. $("form")[0].submit();
600 * @example $("form").submit();
601 * @desc Triggers all submit events registered to the matched form(s), and submits them.
609 * Bind a function to the focus event of each matched element.
611 * @example $("p").focus( function() { alert("Hello"); } );
612 * @before <p>Hello</p>
613 * @result <p onfocus="alert('Hello');">Hello</p>
617 * @param Function fn A function to bind to the focus event on each of the matched elements.
622 * Trigger the focus event of each matched element. This causes all of the functions
623 * that have been bound to thet focus event to be executed.
625 * Note: This does not execute the focus method of the underlying elements! If you need to
626 * focus an element via code, you have to use the DOM method, eg. $("#myinput")[0].focus();
628 * @example $("p").focus();
629 * @before <p onfocus="alert('Hello');">Hello</p>
630 * @result alert('Hello');
638 * Bind a function to the keydown event of each matched element.
640 * @example $("p").keydown( function() { alert("Hello"); } );
641 * @before <p>Hello</p>
642 * @result <p onkeydown="alert('Hello');">Hello</p>
646 * @param Function fn A function to bind to the keydown event on each of the matched elements.
651 * Bind a function to the dblclick event of each matched element.
653 * @example $("p").dblclick( function() { alert("Hello"); } );
654 * @before <p>Hello</p>
655 * @result <p ondblclick="alert('Hello');">Hello</p>
659 * @param Function fn A function to bind to the dblclick event on each of the matched elements.
664 * Bind a function to the keypress event of each matched element.
666 * @example $("p").keypress( function() { alert("Hello"); } );
667 * @before <p>Hello</p>
668 * @result <p onkeypress="alert('Hello');">Hello</p>
672 * @param Function fn A function to bind to the keypress event on each of the matched elements.
677 * Bind a function to the error event of each matched element.
679 * @example $("p").error( function() { alert("Hello"); } );
680 * @before <p>Hello</p>
681 * @result <p onerror="alert('Hello');">Hello</p>
685 * @param Function fn A function to bind to the error event on each of the matched elements.
690 * Bind a function to the blur event of each matched element.
692 * @example $("p").blur( function() { alert("Hello"); } );
693 * @before <p>Hello</p>
694 * @result <p onblur="alert('Hello');">Hello</p>
698 * @param Function fn A function to bind to the blur event on each of the matched elements.
703 * Trigger the blur event of each matched element. This causes all of the functions
704 * that have been bound to that blur event to be executed, and calls the browser's
705 * default blur action on the matching element(s). This default action can be prevented
706 * by returning false from one of the functions bound to the blur event.
708 * Note: This does not execute the blur method of the underlying elements! If you need to
709 * blur an element via code, you have to use the DOM method, eg. $("#myinput")[0].blur();
711 * @example $("p").blur();
712 * @before <p onblur="alert('Hello');">Hello</p>
713 * @result alert('Hello');
721 * Bind a function to the load event of each matched element.
723 * @example $("p").load( function() { alert("Hello"); } );
724 * @before <p>Hello</p>
725 * @result <p onload="alert('Hello');">Hello</p>
729 * @param Function fn A function to bind to the load event on each of the matched elements.
734 * Bind a function to the select event of each matched element.
736 * @example $("p").select( function() { alert("Hello"); } );
737 * @before <p>Hello</p>
738 * @result <p onselect="alert('Hello');">Hello</p>
742 * @param Function fn A function to bind to the select event on each of the matched elements.
747 * Trigger the select event of each matched element. This causes all of the functions
748 * that have been bound to that select event to be executed, and calls the browser's
749 * default select action on the matching element(s). This default action can be prevented
750 * by returning false from one of the functions bound to the select event.
752 * @example $("p").select();
753 * @before <p onselect="alert('Hello');">Hello</p>
754 * @result alert('Hello');
762 * Bind a function to the mouseup event of each matched element.
764 * @example $("p").mouseup( function() { alert("Hello"); } );
765 * @before <p>Hello</p>
766 * @result <p onmouseup="alert('Hello');">Hello</p>
770 * @param Function fn A function to bind to the mouseup event on each of the matched elements.
775 * Bind a function to the unload event of each matched element.
777 * @example $("p").unload( function() { alert("Hello"); } );
778 * @before <p>Hello</p>
779 * @result <p onunload="alert('Hello');">Hello</p>
783 * @param Function fn A function to bind to the unload event on each of the matched elements.
788 * Bind a function to the change event of each matched element.
790 * @example $("p").change( function() { alert("Hello"); } );
791 * @before <p>Hello</p>
792 * @result <p onchange="alert('Hello');">Hello</p>
796 * @param Function fn A function to bind to the change event on each of the matched elements.
801 * Bind a function to the mouseout event of each matched element.
803 * @example $("p").mouseout( function() { alert("Hello"); } );
804 * @before <p>Hello</p>
805 * @result <p onmouseout="alert('Hello');">Hello</p>
809 * @param Function fn A function to bind to the mouseout event on each of the matched elements.
814 * Bind a function to the keyup event of each matched element.
816 * @example $("p").keyup( function() { alert("Hello"); } );
817 * @before <p>Hello</p>
818 * @result <p onkeyup="alert('Hello');">Hello</p>
822 * @param Function fn A function to bind to the keyup event on each of the matched elements.
827 * Bind a function to the click event of each matched element.
829 * @example $("p").click( function() { alert("Hello"); } );
830 * @before <p>Hello</p>
831 * @result <p onclick="alert('Hello');">Hello</p>
835 * @param Function fn A function to bind to the click event on each of the matched elements.
840 * Trigger the click event of each matched element. This causes all of the functions
841 * that have been bound to thet click event to be executed.
843 * @example $("p").click();
844 * @before <p onclick="alert('Hello');">Hello</p>
845 * @result alert('Hello');
853 * Bind a function to the resize event of each matched element.
855 * @example $("p").resize( function() { alert("Hello"); } );
856 * @before <p>Hello</p>
857 * @result <p onresize="alert('Hello');">Hello</p>
861 * @param Function fn A function to bind to the resize event on each of the matched elements.
866 * Bind a function to the mousemove event of each matched element.
868 * @example $("p").mousemove( function() { alert("Hello"); } );
869 * @before <p>Hello</p>
870 * @result <p onmousemove="alert('Hello');">Hello</p>
874 * @param Function fn A function to bind to the mousemove event on each of the matched elements.
879 * Bind a function to the mousedown event of each matched element.
881 * @example $("p").mousedown( function() { alert("Hello"); } );
882 * @before <p>Hello</p>
883 * @result <p onmousedown="alert('Hello');">Hello</p>
887 * @param Function fn A function to bind to the mousedown event on each of the matched elements.
892 * Bind a function to the mouseover event of each matched element.
894 * @example $("p").mouseover( function() { alert("Hello"); } );
895 * @before <p>Hello</p>
896 * @result <p onmouseover="alert('Hello');">Hello</p>
900 * @param Function fn A function to bind to the mousedown event on each of the matched elements.
903 jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
904 "mousedown,mouseup,mousemove,mouseover,mouseout,change,select," +
905 "submit,keydown,keypress,keyup,error").split(","), function(i,o){
907 // Handle event binding
908 jQuery.fn[o] = function(f){
909 return f ? this.bind(o, f) : this.trigger(o);
914 // If Mozilla is used
915 if ( jQuery.browser.mozilla || jQuery.browser.opera )
916 // Use the handy event callback
917 document.addEventListener( "DOMContentLoaded", jQuery.ready, false );
919 // If IE is used, use the excellent hack by Matthias Miller
920 // http://www.outofhanwell.com/blog/index.php?title=the_window_onload_problem_revisited
921 else if ( jQuery.browser.msie ) {
923 // Only works if you document.write() it
924 document.write("<scr" + "ipt id=__ie_init defer=true " +
925 "src=//:><\/script>");
927 // Use the defer script hack
928 var script = document.getElementById("__ie_init");
930 // script does not exist if jQuery is loaded dynamically
932 script.onreadystatechange = function() {
933 if ( this.readyState != "complete" ) return;
941 } else if ( jQuery.browser.safari )
942 // Continually check to see if the document.readyState is valid
943 jQuery.safariTimer = setInterval(function(){
944 // loaded and complete are both valid states
945 if ( document.readyState == "loaded" ||
946 document.readyState == "complete" ) {
948 // If either one are found, remove the timer
949 clearInterval( jQuery.safariTimer );
950 jQuery.safariTimer = null;
952 // and execute any waiting functions
957 // A fallback to window.onload, that will always work
958 jQuery.event.add( window, "load", jQuery.ready );
962 // Clean up after IE to avoid memory leaks
963 if (jQuery.browser.msie)
964 jQuery(window).one("unload", function() {
965 var global = jQuery.event.global;
966 for ( var type in global ) {
967 var els = global[type], i = els.length;
968 if ( i && type != 'unload' )
970 jQuery.event.remove(els[i-1], type);