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
36 handler.guid = this.guid++;
38 // Init the element's event structure
42 // Get the current list of functions bound to this event
43 var handlers = element.$events[type];
45 // Init the event handler queue
47 handlers = element.$events[type] = {};
49 // Add the function to the element's handler list
50 handlers[handler.guid] = handler;
52 // And bind the global event handler to the element
53 if (element.addEventListener)
54 element.addEventListener(type, this.handle, false);
55 else if (element.attachEvent)
56 element.attachEvent("on" + type, this.handle, false);
58 // Remember the function in a global list (for triggering)
59 if (!this.global[type])
60 this.global[type] = [];
61 this.global[type].push( element );
67 // Detach an event or set of events from an element
68 remove: function(element, type, handler) {
69 var events = element.$events, ret;
72 // type is actually an event object here
73 if ( type && type.type ) {
74 handler = type.handler;
79 for ( type in events )
80 this.remove( element, type );
82 } else if ( events[type] ) {
83 // remove the given handler for the given type
85 delete events[type][handler.guid];
87 // remove all handlers for the given type
89 for ( handler in element.$events[type] )
90 delete events[type][handler];
92 // remove generic event handler if no more handlers exist
93 for ( ret in events[type] ) break;
96 if (element.removeEventListener)
97 element.removeEventListener(type, this.handle, false);
98 else if (element.detachEvent)
99 element.detachEvent("on" + type, this.handle, false);
104 // Remove the expando if it's no longer used
105 for ( ret in events ) break;
107 element.$events = null;
111 trigger: function(type, data, element) {
112 // Clone the incoming data, if any
113 data = jQuery.makeArray(data || []);
115 // Handle a global trigger
117 jQuery.each( this.global[type] || [], function(){
118 jQuery.event.trigger( type, data, this );
121 // Handle triggering a single element
123 var val, ret, fn = jQuery.isFunction( element[ type ] );
125 // Pass along a fake event
126 data.unshift( this.fix({ type: type, target: element }) );
129 if ( (val = this.handle.apply( element, data )) !== false )
130 this.triggered = true;
132 if ( fn && val !== false && !jQuery.nodeName(element, 'a') )
135 this.triggered = false;
139 handle: function(event) {
140 // Handle the second event of a trigger and when
141 // an event is called after a page has unloaded
142 if ( typeof jQuery == "undefined" || jQuery.event.triggered ) return;
144 // Empty object is for triggered events with no data
145 event = jQuery.event.fix( event || window.event || {} );
147 // returned undefined or false
150 var c = this.$events[event.type];
152 var args = [].slice.call( arguments, 1 );
153 args.unshift( event );
156 // Pass in a reference to the handler function itself
157 // So that we can later remove it
158 args[0].handler = c[j];
159 args[0].data = c[j].data;
161 if ( c[j].apply( this, args ) === false ) {
162 event.preventDefault();
163 event.stopPropagation();
168 // Clean up added properties in IE to prevent memory leak
169 if (jQuery.browser.msie) event.target = event.preventDefault = event.stopPropagation = event.handler = event.data = null;
174 fix: function(event) {
175 // Fix target property, if necessary
176 if ( !event.target && event.srcElement )
177 event.target = event.srcElement;
179 // Calculate pageX/Y if missing and clientX/Y available
180 if ( event.pageX == undefined && event.clientX != undefined ) {
181 var e = document.documentElement, b = document.body;
182 event.pageX = event.clientX + (e.scrollLeft || b.scrollLeft);
183 event.pageY = event.clientY + (e.scrollTop || b.scrollTop);
186 // check if target is a textnode (safari)
187 if (jQuery.browser.safari && event.target.nodeType == 3) {
188 // store a copy of the original event object
189 // and clone because target is read only
190 var originalEvent = event;
191 event = jQuery.extend({}, originalEvent);
193 // get parentnode from textnode
194 event.target = originalEvent.target.parentNode;
196 // add preventDefault and stopPropagation since
197 // they will not work on the clone
198 event.preventDefault = function() {
199 return originalEvent.preventDefault();
201 event.stopPropagation = function() {
202 return originalEvent.stopPropagation();
206 // fix preventDefault and stopPropagation
207 if (!event.preventDefault)
208 event.preventDefault = function() {
209 this.returnValue = false;
212 if (!event.stopPropagation)
213 event.stopPropagation = function() {
214 this.cancelBubble = true;
224 * Binds a handler to a particular event (like click) for each matched element.
225 * The event handler is passed an event object that you can use to prevent
226 * default behaviour. To stop both default action and event bubbling, your handler
227 * has to return false.
229 * In most cases, you can define your event handlers as anonymous functions
230 * (see first example). In cases where that is not possible, you can pass additional
231 * data as the second parameter (and the handler function as the third), see
234 * @example $("p").bind("click", function(){
235 * alert( $(this).text() );
237 * @before <p>Hello</p>
238 * @result alert("Hello")
240 * @example function handler(event) {
241 * alert(event.data.foo);
243 * $("p").bind("click", {foo: "bar"}, handler)
244 * @result alert("bar")
245 * @desc Pass some additional data to the event handler.
247 * @example $("form").bind("submit", function() { return false; })
248 * @desc Cancel a default action and prevent it from bubbling by returning false
249 * from your function.
251 * @example $("form").bind("submit", function(event){
252 * event.preventDefault();
254 * @desc Cancel only the default action by using the preventDefault method.
257 * @example $("form").bind("submit", function(event){
258 * event.stopPropagation();
260 * @desc Stop only an event from bubbling by using the stopPropagation method.
264 * @param String type An event type
265 * @param Object data (optional) Additional data passed to the event handler as event.data
266 * @param Function fn A function to bind to the event on each of the set of matched elements
269 bind: function( type, data, fn ) {
270 return this.each(function(){
271 jQuery.event.add( this, type, fn || data, data );
276 * Binds a handler to a particular event (like click) for each matched element.
277 * The handler is executed only once for each element. Otherwise, the same rules
278 * as described in bind() apply.
279 The event handler is passed an event object that you can use to prevent
280 * default behaviour. To stop both default action and event bubbling, your handler
281 * has to return false.
283 * In most cases, you can define your event handlers as anonymous functions
284 * (see first example). In cases where that is not possible, you can pass additional
285 * data as the second paramter (and the handler function as the third), see
288 * @example $("p").one("click", function(){
289 * alert( $(this).text() );
291 * @before <p>Hello</p>
292 * @result alert("Hello")
296 * @param String type An event type
297 * @param Object data (optional) Additional data passed to the event handler as event.data
298 * @param Function fn A function to bind to the event on each of the set of matched elements
301 one: function( type, data, fn ) {
302 return this.each(function(){
303 jQuery.event.add( this, type, function(event) {
304 jQuery(this).unbind(event);
305 return (fn || data).apply( this, arguments);
311 * The opposite of bind, removes a bound event from each of the matched
314 * Without any arguments, all bound events are removed.
316 * If the type is provided, all bound events of that type are removed.
318 * If the function that was passed to bind is provided as the second argument,
319 * only that specific event handler is removed.
321 * @example $("p").unbind()
322 * @before <p onclick="alert('Hello');">Hello</p>
323 * @result [ <p>Hello</p> ]
325 * @example $("p").unbind( "click" )
326 * @before <p onclick="alert('Hello');">Hello</p>
327 * @result [ <p>Hello</p> ]
329 * @example $("p").unbind( "click", function() { alert("Hello"); } )
330 * @before <p onclick="alert('Hello');">Hello</p>
331 * @result [ <p>Hello</p> ]
335 * @param String type (optional) An event type
336 * @param Function fn (optional) A function to unbind from the event on each of the set of matched elements
339 unbind: function( type, fn ) {
340 return this.each(function(){
341 jQuery.event.remove( this, type, fn );
346 * Trigger a type of event on every matched element. This will also cause
347 * the default action of the browser with the same name (if one exists)
348 * to be executed. For example, passing 'submit' to the trigger()
349 * function will also cause the browser to submit the form. This
350 * default action can be prevented by returning false from one of
351 * the functions bound to the event.
353 * You can also trigger custom events registered with bind.
355 * @example $("p").trigger("click")
356 * @before <p click="alert('hello')">Hello</p>
357 * @result alert('hello')
359 * @example $("p").click(function(event, a, b) {
360 * // when a normal click fires, a and b are undefined
361 * // for a trigger like below a refers too "foo" and b refers to "bar"
362 * }).trigger("click", ["foo", "bar"]);
363 * @desc Example of how to pass arbitrary data to an event
365 * @example $("p").bind("myEvent",function(event,message1,message2) {
366 * alert(message1 + ' ' + message2);
368 * $("p").trigger("myEvent",["Hello","World"]);
369 * @result alert('Hello World') // One for each paragraph
373 * @param String type An event type to trigger.
374 * @param Array data (optional) Additional data to pass as arguments (after the event object) to the event handler
377 trigger: function( type, data ) {
378 return this.each(function(){
379 jQuery.event.trigger( type, data, this );
384 * Toggle between two function calls every other click.
385 * Whenever a matched element is clicked, the first specified function
386 * is fired, when clicked again, the second is fired. All subsequent
387 * clicks continue to rotate through the two functions.
389 * Use unbind("click") to remove.
391 * @example $("p").toggle(function(){
392 * $(this).addClass("selected");
394 * $(this).removeClass("selected");
399 * @param Function even The function to execute on every even click.
400 * @param Function odd The function to execute on every odd click.
404 // Save reference to arguments for access in closure
407 return this.click(function(e) {
408 // Figure out which function to execute
409 this.lastToggle = this.lastToggle == 0 ? 1 : 0;
411 // Make sure that clicks stop
414 // and execute the function
415 return a[this.lastToggle].apply( this, [e] ) || false;
420 * A method for simulating hovering (moving the mouse on, and off,
421 * an object). This is a custom method which provides an 'in' to a
424 * Whenever the mouse cursor is moved over a matched
425 * element, the first specified function is fired. Whenever the mouse
426 * moves off of the element, the second specified function fires.
427 * Additionally, checks are in place to see if the mouse is still within
428 * the specified element itself (for example, an image inside of a div),
429 * and if it is, it will continue to 'hover', and not move out
430 * (a common error in using a mouseout event handler).
432 * @example $("p").hover(function(){
433 * $(this).addClass("hover");
435 * $(this).removeClass("hover");
440 * @param Function over The function to fire whenever the mouse is moved over a matched element.
441 * @param Function out The function to fire whenever the mouse is moved off of a matched element.
444 hover: function(f,g) {
446 // A private function for handling mouse 'hovering'
447 function handleHover(e) {
448 // Check if mouse(over|out) are still within the same parent element
449 var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
451 // Traverse up the tree
452 while ( p && p != this ) try { p = p.parentNode } catch(e) { p = this; };
454 // If we actually just moused on to a sub-element, ignore it
455 if ( p == this ) return false;
457 // Execute the right function
458 return (e.type == "mouseover" ? f : g).apply(this, [e]);
461 // Bind the function to the two event listeners
462 return this.mouseover(handleHover).mouseout(handleHover);
466 * Bind a function to be executed whenever the DOM is ready to be
467 * traversed and manipulated. This is probably the most important
468 * function included in the event module, as it can greatly improve
469 * the response times of your web applications.
471 * In a nutshell, this is a solid replacement for using window.onload,
472 * and attaching a function to that. By using this method, your bound function
473 * will be called the instant the DOM is ready to be read and manipulated,
474 * which is when what 99.99% of all JavaScript code needs to run.
476 * There is one argument passed to the ready event handler: A reference to
477 * the jQuery function. You can name that argument whatever you like, and
478 * can therefore stick with the $ alias without risk of naming collisions.
480 * Please ensure you have no code in your <body> onload event handler,
481 * otherwise $(document).ready() may not fire.
483 * You can have as many $(document).ready events on your page as you like.
484 * The functions are then executed in the order they were added.
486 * @example $(document).ready(function(){ Your code here... });
488 * @example jQuery(function($) {
489 * // Your code using failsafe $ alias here...
491 * @desc Uses both the [[Core#.24.28_fn_.29|shortcut]] for $(document).ready() and the argument
492 * to write failsafe jQuery code using the $ alias, without relying on the
497 * @param Function fn The function to be executed when the DOM is ready.
499 * @see $.noConflict()
503 // If the DOM is already ready
504 if ( jQuery.isReady )
505 // Execute the function immediately
506 f.apply( document, [jQuery] );
508 // Otherwise, remember the function for later
510 // Add the function to the wait list
511 jQuery.readyList.push( function() { return f.apply(this, [jQuery]) } );
520 * All the code that makes DOM Ready work nicely.
525 // Handle when the DOM is ready
527 // Make sure that the DOM is not already loaded
528 if ( !jQuery.isReady ) {
529 // Remember that the DOM is ready
530 jQuery.isReady = true;
532 // If there are functions bound, to execute
533 if ( jQuery.readyList ) {
534 // Execute all of them
535 jQuery.each( jQuery.readyList, function(){
536 this.apply( document );
539 // Reset the list of functions
540 jQuery.readyList = null;
542 // Remove event lisenter to avoid memory leak
543 if ( jQuery.browser.mozilla || jQuery.browser.opera )
544 document.removeEventListener( "DOMContentLoaded", jQuery.ready, false );
552 * Bind a function to the scroll event of each matched element.
554 * @example $("p").scroll( function() { alert("Hello"); } );
555 * @before <p>Hello</p>
556 * @result <p onscroll="alert('Hello');">Hello</p>
560 * @param Function fn A function to bind to the scroll event on each of the matched elements.
565 * Bind a function to the submit event of each matched element.
567 * @example $("#myform").submit( function() {
568 * return $("input", this).val().length > 0;
570 * @before <form id="myform"><input /></form>
571 * @desc Prevents the form submission when the input has no value entered.
575 * @param Function fn A function to bind to the submit event on each of the matched elements.
580 * Trigger the submit event of each matched element. This causes all of the functions
581 * that have been bound to that submit event to be executed, and calls the browser's
582 * default submit action on the matching element(s). This default action can be prevented
583 * by returning false from one of the functions bound to the submit event.
585 * Note: This does not execute the submit method of the form element! If you need to
586 * submit the form via code, you have to use the DOM method, eg. $("form")[0].submit();
588 * @example $("form").submit();
589 * @desc Triggers all submit events registered to the matched form(s), and submits them.
597 * Bind a function to the focus event of each matched element.
599 * @example $("p").focus( function() { alert("Hello"); } );
600 * @before <p>Hello</p>
601 * @result <p onfocus="alert('Hello');">Hello</p>
605 * @param Function fn A function to bind to the focus event on each of the matched elements.
610 * Trigger the focus event of each matched element. This causes all of the functions
611 * that have been bound to thet focus event to be executed.
613 * Note: This does not execute the focus method of the underlying elements! If you need to
614 * focus an element via code, you have to use the DOM method, eg. $("#myinput")[0].focus();
616 * @example $("p").focus();
617 * @before <p onfocus="alert('Hello');">Hello</p>
618 * @result alert('Hello');
626 * Bind a function to the keydown event of each matched element.
628 * @example $("p").keydown( function() { alert("Hello"); } );
629 * @before <p>Hello</p>
630 * @result <p onkeydown="alert('Hello');">Hello</p>
634 * @param Function fn A function to bind to the keydown event on each of the matched elements.
639 * Bind a function to the dblclick event of each matched element.
641 * @example $("p").dblclick( function() { alert("Hello"); } );
642 * @before <p>Hello</p>
643 * @result <p ondblclick="alert('Hello');">Hello</p>
647 * @param Function fn A function to bind to the dblclick event on each of the matched elements.
652 * Bind a function to the keypress event of each matched element.
654 * @example $("p").keypress( function() { alert("Hello"); } );
655 * @before <p>Hello</p>
656 * @result <p onkeypress="alert('Hello');">Hello</p>
660 * @param Function fn A function to bind to the keypress event on each of the matched elements.
665 * Bind a function to the error event of each matched element.
667 * @example $("p").error( function() { alert("Hello"); } );
668 * @before <p>Hello</p>
669 * @result <p onerror="alert('Hello');">Hello</p>
673 * @param Function fn A function to bind to the error event on each of the matched elements.
678 * Bind a function to the blur event of each matched element.
680 * @example $("p").blur( function() { alert("Hello"); } );
681 * @before <p>Hello</p>
682 * @result <p onblur="alert('Hello');">Hello</p>
686 * @param Function fn A function to bind to the blur event on each of the matched elements.
691 * Trigger the blur event of each matched element. This causes all of the functions
692 * that have been bound to that blur event to be executed, and calls the browser's
693 * default blur action on the matching element(s). This default action can be prevented
694 * by returning false from one of the functions bound to the blur event.
696 * Note: This does not execute the blur method of the underlying elements! If you need to
697 * blur an element via code, you have to use the DOM method, eg. $("#myinput")[0].blur();
699 * @example $("p").blur();
700 * @before <p onblur="alert('Hello');">Hello</p>
701 * @result alert('Hello');
709 * Bind a function to the load event of each matched element.
711 * @example $("p").load( function() { alert("Hello"); } );
712 * @before <p>Hello</p>
713 * @result <p onload="alert('Hello');">Hello</p>
717 * @param Function fn A function to bind to the load event on each of the matched elements.
722 * Bind a function to the select event of each matched element.
724 * @example $("p").select( function() { alert("Hello"); } );
725 * @before <p>Hello</p>
726 * @result <p onselect="alert('Hello');">Hello</p>
730 * @param Function fn A function to bind to the select event on each of the matched elements.
735 * Trigger the select event of each matched element. This causes all of the functions
736 * that have been bound to that select event to be executed, and calls the browser's
737 * default select action on the matching element(s). This default action can be prevented
738 * by returning false from one of the functions bound to the select event.
740 * @example $("p").select();
741 * @before <p onselect="alert('Hello');">Hello</p>
742 * @result alert('Hello');
750 * Bind a function to the mouseup event of each matched element.
752 * @example $("p").mouseup( function() { alert("Hello"); } );
753 * @before <p>Hello</p>
754 * @result <p onmouseup="alert('Hello');">Hello</p>
758 * @param Function fn A function to bind to the mouseup event on each of the matched elements.
763 * Bind a function to the unload event of each matched element.
765 * @example $("p").unload( function() { alert("Hello"); } );
766 * @before <p>Hello</p>
767 * @result <p onunload="alert('Hello');">Hello</p>
771 * @param Function fn A function to bind to the unload event on each of the matched elements.
776 * Bind a function to the change event of each matched element.
778 * @example $("p").change( function() { alert("Hello"); } );
779 * @before <p>Hello</p>
780 * @result <p onchange="alert('Hello');">Hello</p>
784 * @param Function fn A function to bind to the change event on each of the matched elements.
789 * Bind a function to the mouseout event of each matched element.
791 * @example $("p").mouseout( function() { alert("Hello"); } );
792 * @before <p>Hello</p>
793 * @result <p onmouseout="alert('Hello');">Hello</p>
797 * @param Function fn A function to bind to the mouseout event on each of the matched elements.
802 * Bind a function to the keyup event of each matched element.
804 * @example $("p").keyup( function() { alert("Hello"); } );
805 * @before <p>Hello</p>
806 * @result <p onkeyup="alert('Hello');">Hello</p>
810 * @param Function fn A function to bind to the keyup event on each of the matched elements.
815 * Bind a function to the click event of each matched element.
817 * @example $("p").click( function() { alert("Hello"); } );
818 * @before <p>Hello</p>
819 * @result <p onclick="alert('Hello');">Hello</p>
823 * @param Function fn A function to bind to the click event on each of the matched elements.
828 * Trigger the click event of each matched element. This causes all of the functions
829 * that have been bound to thet click event to be executed.
831 * @example $("p").click();
832 * @before <p onclick="alert('Hello');">Hello</p>
833 * @result alert('Hello');
841 * Bind a function to the resize event of each matched element.
843 * @example $("p").resize( function() { alert("Hello"); } );
844 * @before <p>Hello</p>
845 * @result <p onresize="alert('Hello');">Hello</p>
849 * @param Function fn A function to bind to the resize event on each of the matched elements.
854 * Bind a function to the mousemove event of each matched element.
856 * @example $("p").mousemove( function() { alert("Hello"); } );
857 * @before <p>Hello</p>
858 * @result <p onmousemove="alert('Hello');">Hello</p>
862 * @param Function fn A function to bind to the mousemove event on each of the matched elements.
867 * Bind a function to the mousedown event of each matched element.
869 * @example $("p").mousedown( function() { alert("Hello"); } );
870 * @before <p>Hello</p>
871 * @result <p onmousedown="alert('Hello');">Hello</p>
875 * @param Function fn A function to bind to the mousedown event on each of the matched elements.
880 * Bind a function to the mouseover event of each matched element.
882 * @example $("p").mouseover( function() { alert("Hello"); } );
883 * @before <p>Hello</p>
884 * @result <p onmouseover="alert('Hello');">Hello</p>
888 * @param Function fn A function to bind to the mousedown event on each of the matched elements.
891 jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
892 "mousedown,mouseup,mousemove,mouseover,mouseout,change,select," +
893 "submit,keydown,keypress,keyup,error").split(","), function(i,o){
895 // Handle event binding
896 jQuery.fn[o] = function(f){
897 return f ? this.bind(o, f) : this.trigger(o);
902 // If Mozilla is used
903 if ( jQuery.browser.mozilla || jQuery.browser.opera )
904 // Use the handy event callback
905 document.addEventListener( "DOMContentLoaded", jQuery.ready, false );
907 // If IE is used, use the excellent hack by Matthias Miller
908 // http://www.outofhanwell.com/blog/index.php?title=the_window_onload_problem_revisited
909 else if ( jQuery.browser.msie ) {
911 // Only works if you document.write() it
912 document.write("<scr" + "ipt id=__ie_init defer=true " +
913 "src=//:><\/script>");
915 // Use the defer script hack
916 var script = document.getElementById("__ie_init");
918 // script does not exist if jQuery is loaded dynamically
920 script.onreadystatechange = function() {
921 if ( this.readyState != "complete" ) return;
922 this.parentNode.removeChild( this );
930 } else if ( jQuery.browser.safari )
931 // Continually check to see if the document.readyState is valid
932 jQuery.safariTimer = setInterval(function(){
933 // loaded and complete are both valid states
934 if ( document.readyState == "loaded" ||
935 document.readyState == "complete" ) {
937 // If either one are found, remove the timer
938 clearInterval( jQuery.safariTimer );
939 jQuery.safariTimer = null;
941 // and execute any waiting functions
946 // A fallback to window.onload, that will always work
947 jQuery.event.add( window, "load", jQuery.ready );
951 // Clean up after IE to avoid memory leaks
952 if (jQuery.browser.msie)
953 jQuery(window).one("unload", function() {
954 var global = jQuery.event.global;
955 for ( var type in global ) {
956 var els = global[type], i = els.length;
957 if ( i && type != 'unload' )
959 jQuery.event.remove(els[i-1], type);