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
20 // Make sure that the function being executed has a unique ID
22 handler.guid = this.guid++;
24 // Init the element's event structure
28 // Get the current list of functions bound to this event
29 var handlers = element.events[type];
31 // If it hasn't been initialized yet
33 // Init the event handler queue
34 handlers = element.events[type] = {};
36 // Remember an existing handler, if it's already there
37 if (element["on" + type])
38 handlers[0] = element["on" + type];
41 // Add the function to the element's handler list
42 handlers[handler.guid] = handler;
44 // And bind the global event handler to the element
45 element["on" + type] = this.handle;
47 // Remember the function in a global list (for triggering)
48 if (!this.global[type])
49 this.global[type] = [];
50 this.global[type].push( element );
56 // Detach an event or set of events from an element
57 remove: function(element, type, handler) {
59 if ( type && type.type )
60 delete element.events[ type.type ][ type.handler.guid ];
61 else if (type && element.events[type])
63 delete element.events[type][handler.guid];
65 for ( var i in element.events[type] )
66 delete element.events[type][i];
68 for ( var j in element.events )
69 this.remove( element, j );
72 trigger: function(type,data,element) {
73 // Clone the incoming data, if any
74 data = jQuery.makeArray(data || []);
76 // Handle a global trigger
78 var g = this.global[type];
80 for ( var i = 0, gl = g.length; i < gl; i++ )
81 this.trigger( type, data, g[i] );
83 // Handle triggering a single element
84 } else if ( element["on" + type] ) {
85 // Pass along a fake event
86 data.unshift( this.fix({ type: type, target: element }) );
89 var val = element["on" + type].apply( element, data );
91 if ( val !== false && jQuery.isFunction( element[ type ] ) )
96 handle: function(event) {
97 if ( typeof jQuery == "undefined" ) return false;
99 // Empty object is for triggered events with no data
100 event = jQuery.event.fix( event || window.event || {} );
102 // returned undefined or false
105 var c = this.events[event.type];
107 var args = [].slice.call( arguments, 1 );
108 args.unshift( event );
111 // Pass in a reference to the handler function itself
112 // So that we can later remove it
113 args[0].handler = c[j];
114 args[0].data = c[j].data;
116 if ( c[j].apply( this, args ) === false ) {
117 event.preventDefault();
118 event.stopPropagation();
123 // Clean up added properties in IE to prevent memory leak
124 if (jQuery.browser.msie) event.target = event.preventDefault = event.stopPropagation = event.handler = event.data = null;
129 fix: function(event) {
130 // Fix target property, if necessary
131 if ( !event.target && event.srcElement )
132 event.target = event.srcElement;
134 // Calculate pageX/Y if missing and clientX/Y available
135 if ( event.pageX == undefined && event.clientX != undefined ) {
136 var e = document.documentElement, b = document.body;
137 event.pageX = event.clientX + (e.scrollLeft || b.scrollLeft);
138 event.pageY = event.clientY + (e.scrollTop || b.scrollTop);
141 // check if target is a textnode (safari)
142 if (jQuery.browser.safari && event.target.nodeType == 3) {
143 // store a copy of the original event object
144 // and clone because target is read only
145 var originalEvent = event;
146 event = jQuery.extend({}, originalEvent);
148 // get parentnode from textnode
149 event.target = originalEvent.target.parentNode;
151 // add preventDefault and stopPropagation since
152 // they will not work on the clone
153 event.preventDefault = function() {
154 return originalEvent.preventDefault();
156 event.stopPropagation = function() {
157 return originalEvent.stopPropagation();
161 // fix preventDefault and stopPropagation
162 if (!event.preventDefault)
163 event.preventDefault = function() {
164 this.returnValue = false;
167 if (!event.stopPropagation)
168 event.stopPropagation = function() {
169 this.cancelBubble = true;
179 * Binds a handler to a particular event (like click) for each matched element.
180 * The event handler is passed an event object that you can use to prevent
181 * default behaviour. To stop both default action and event bubbling, your handler
182 * has to return false.
184 * In most cases, you can define your event handlers as anonymous functions
185 * (see first example). In cases where that is not possible, you can pass additional
186 * data as the second paramter (and the handler function as the third), see
189 * @example $("p").bind("click", function(){
190 * alert( $(this).text() );
192 * @before <p>Hello</p>
193 * @result alert("Hello")
195 * @example function handler(event) {
196 * alert(event.data.foo);
198 * $("p").bind("click", {foo: "bar"}, handler)
199 * @result alert("bar")
200 * @desc Pass some additional data to the event handler.
202 * @example $("form").bind("submit", function() { return false; })
203 * @desc Cancel a default action and prevent it from bubbling by returning false
204 * from your function.
206 * @example $("form").bind("submit", function(event){
207 * event.preventDefault();
209 * @desc Cancel only the default action by using the preventDefault method.
212 * @example $("form").bind("submit", function(event){
213 * event.stopPropagation();
215 * @desc Stop only an event from bubbling by using the stopPropagation method.
219 * @param String type An event type
220 * @param Object data (optional) Additional data passed to the event handler as event.data
221 * @param Function fn A function to bind to the event on each of the set of matched elements
224 bind: function( type, data, fn ) {
225 return this.each(function(){
226 jQuery.event.add( this, type, fn || data, data );
231 * Binds a handler to a particular event (like click) for each matched element.
232 * The handler is executed only once for each element. Otherwise, the same rules
233 * as described in bind() apply.
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 paramter (and the handler function as the third), see
243 * @example $("p").one("click", function(){
244 * alert( $(this).text() );
246 * @before <p>Hello</p>
247 * @result alert("Hello")
251 * @param String type An event type
252 * @param Object data (optional) Additional data passed to the event handler as event.data
253 * @param Function fn A function to bind to the event on each of the set of matched elements
256 one: function( type, data, fn ) {
257 return this.each(function(){
258 jQuery.event.add( this, type, function(event) {
259 jQuery(this).unbind(event);
260 return (fn || data).apply( this, arguments);
266 * The opposite of bind, removes a bound event from each of the matched
269 * Without any arguments, all bound events are removed.
271 * If the type is provided, all bound events of that type are removed.
273 * If the function that was passed to bind is provided as the second argument,
274 * only that specific event handler is removed.
276 * @example $("p").unbind()
277 * @before <p onclick="alert('Hello');">Hello</p>
278 * @result [ <p>Hello</p> ]
280 * @example $("p").unbind( "click" )
281 * @before <p onclick="alert('Hello');">Hello</p>
282 * @result [ <p>Hello</p> ]
284 * @example $("p").unbind( "click", function() { alert("Hello"); } )
285 * @before <p onclick="alert('Hello');">Hello</p>
286 * @result [ <p>Hello</p> ]
290 * @param String type (optional) An event type
291 * @param Function fn (optional) A function to unbind from the event on each of the set of matched elements
294 unbind: function( type, fn ) {
295 return this.each(function(){
296 jQuery.event.remove( this, type, fn );
301 * Trigger a type of event on every matched element.
303 * @example $("p").trigger("click")
304 * @before <p click="alert('hello')">Hello</p>
305 * @result alert('hello')
309 * @param String type An event type to trigger.
312 trigger: function( type, data ) {
313 return this.each(function(){
314 jQuery.event.trigger( type, data, this );
319 * Toggle between two function calls every other click.
320 * Whenever a matched element is clicked, the first specified function
321 * is fired, when clicked again, the second is fired. All subsequent
322 * clicks continue to rotate through the two functions.
324 * Use unbind("click") to remove.
326 * @example $("p").toggle(function(){
327 * $(this).addClass("selected");
329 * $(this).removeClass("selected");
334 * @param Function even The function to execute on every even click.
335 * @param Function odd The function to execute on every odd click.
339 // Save reference to arguments for access in closure
342 return this.click(function(e) {
343 // Figure out which function to execute
344 this.lastToggle = this.lastToggle == 0 ? 1 : 0;
346 // Make sure that clicks stop
349 // and execute the function
350 return a[this.lastToggle].apply( this, [e] ) || false;
355 * A method for simulating hovering (moving the mouse on, and off,
356 * an object). This is a custom method which provides an 'in' to a
359 * Whenever the mouse cursor is moved over a matched
360 * element, the first specified function is fired. Whenever the mouse
361 * moves off of the element, the second specified function fires.
362 * Additionally, checks are in place to see if the mouse is still within
363 * the specified element itself (for example, an image inside of a div),
364 * and if it is, it will continue to 'hover', and not move out
365 * (a common error in using a mouseout event handler).
367 * @example $("p").hover(function(){
368 * $(this).addClass("over");
370 * $(this).addClass("out");
375 * @param Function over The function to fire whenever the mouse is moved over a matched element.
376 * @param Function out The function to fire whenever the mouse is moved off of a matched element.
379 hover: function(f,g) {
381 // A private function for handling mouse 'hovering'
382 function handleHover(e) {
383 // Check if mouse(over|out) are still within the same parent element
384 var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
386 // Traverse up the tree
387 while ( p && p != this ) try { p = p.parentNode } catch(e) { p = this; };
389 // If we actually just moused on to a sub-element, ignore it
390 if ( p == this ) return false;
392 // Execute the right function
393 return (e.type == "mouseover" ? f : g).apply(this, [e]);
396 // Bind the function to the two event listeners
397 return this.mouseover(handleHover).mouseout(handleHover);
401 * Bind a function to be executed whenever the DOM is ready to be
402 * traversed and manipulated. This is probably the most important
403 * function included in the event module, as it can greatly improve
404 * the response times of your web applications.
406 * In a nutshell, this is a solid replacement for using window.onload,
407 * and attaching a function to that. By using this method, your bound Function
408 * will be called the instant the DOM is ready to be read and manipulated,
409 * which is exactly what 99.99% of all Javascript code needs to run.
411 * There is one argument passed to the ready event handler: A reference to
412 * the jQuery function. You can name that argument whatever you like, and
413 * can therefore stick with the $ alias without risc of naming collisions.
415 * Please ensure you have no code in your <body> onload event handler,
416 * otherwise $(document).ready() may not fire.
418 * You can have as many $(document).ready events on your page as you like.
419 * The functions are then executed in the order they were added.
421 * @example $(document).ready(function(){ Your code here... });
423 * @example jQuery(function($) {
424 * // Your code using failsafe $ alias here...
426 * @desc Uses both the shortcut for $(document).ready() and the argument
427 * to write failsafe jQuery code using the $ alias, without relying on the
432 * @param Function fn The function to be executed when the DOM is ready.
434 * @see $.noConflict()
438 // If the DOM is already ready
439 if ( jQuery.isReady )
440 // Execute the function immediately
441 f.apply( document, [jQuery] );
443 // Otherwise, remember the function for later
445 // Add the function to the wait list
446 jQuery.readyList.push( function() { return f.apply(this, [jQuery]) } );
455 * All the code that makes DOM Ready work nicely.
460 // Handle when the DOM is ready
462 // Make sure that the DOM is not already loaded
463 if ( !jQuery.isReady ) {
464 // Remember that the DOM is ready
465 jQuery.isReady = true;
467 // If there are functions bound, to execute
468 if ( jQuery.readyList ) {
469 // Execute all of them
470 for ( var i = 0; i < jQuery.readyList.length; i++ )
471 jQuery.readyList[i].apply( document );
473 // Reset the list of functions
474 jQuery.readyList = null;
476 // Remove event lisenter to avoid memory leak
477 if ( jQuery.browser.mozilla || jQuery.browser.opera )
478 document.removeEventListener( "DOMContentLoaded", jQuery.ready, false );
486 * Bind a function to the scroll event of each matched element.
488 * @example $("p").scroll( function() { alert("Hello"); } );
489 * @before <p>Hello</p>
490 * @result <p onscroll="alert('Hello');">Hello</p>
494 * @param Function fn A function to bind to the scroll event on each of the matched elements.
499 * Bind a function to the submit event of each matched element.
501 * @example $("#myform").submit( function() {
502 * return $("input", this).val().length > 0;
504 * @before <form id="myform"><input /></form>
505 * @desc Prevents the form submission when the input has no value entered.
509 * @param Function fn A function to bind to the submit event on each of the matched elements.
514 * Trigger the submit event of each matched element. This causes all of the functions
515 * that have been bound to thet submit event to be executed.
517 * Note: This does not execute the submit method of the form element! If you need to
518 * submit the form via code, you have to use the DOM method, eg. $("form")[0].submit();
520 * @example $("form").submit();
521 * @desc Triggers all submit events registered for forms, but does not submit the form
529 * Bind a function to the focus event of each matched element.
531 * @example $("p").focus( function() { alert("Hello"); } );
532 * @before <p>Hello</p>
533 * @result <p onfocus="alert('Hello');">Hello</p>
537 * @param Function fn A function to bind to the focus event on each of the matched elements.
542 * Trigger the focus event of each matched element. This causes all of the functions
543 * that have been bound to thet focus event to be executed.
545 * Note: This does not execute the focus method of the underlying elements! If you need to
546 * focus an element via code, you have to use the DOM method, eg. $("#myinput")[0].focus();
548 * @example $("p").focus();
549 * @before <p onfocus="alert('Hello');">Hello</p>
550 * @result alert('Hello');
558 * Bind a function to the keydown event of each matched element.
560 * @example $("p").keydown( function() { alert("Hello"); } );
561 * @before <p>Hello</p>
562 * @result <p onkeydown="alert('Hello');">Hello</p>
566 * @param Function fn A function to bind to the keydown event on each of the matched elements.
571 * Bind a function to the dblclick event of each matched element.
573 * @example $("p").dblclick( function() { alert("Hello"); } );
574 * @before <p>Hello</p>
575 * @result <p ondblclick="alert('Hello');">Hello</p>
579 * @param Function fn A function to bind to the dblclick event on each of the matched elements.
584 * Bind a function to the keypress event of each matched element.
586 * @example $("p").keypress( function() { alert("Hello"); } );
587 * @before <p>Hello</p>
588 * @result <p onkeypress="alert('Hello');">Hello</p>
592 * @param Function fn A function to bind to the keypress event on each of the matched elements.
597 * Bind a function to the error event of each matched element.
599 * @example $("p").error( function() { alert("Hello"); } );
600 * @before <p>Hello</p>
601 * @result <p onerror="alert('Hello');">Hello</p>
605 * @param Function fn A function to bind to the error event on each of the matched elements.
610 * Bind a function to the blur event of each matched element.
612 * @example $("p").blur( function() { alert("Hello"); } );
613 * @before <p>Hello</p>
614 * @result <p onblur="alert('Hello');">Hello</p>
618 * @param Function fn A function to bind to the blur event on each of the matched elements.
623 * Trigger the blur event of each matched element. This causes all of the functions
624 * that have been bound to thet blur event to be executed.
626 * Note: This does not execute the blur method of the underlying elements! If you need to
627 * blur an element via code, you have to use the DOM method, eg. $("#myinput")[0].blur();
629 * @example $("p").blur();
630 * @before <p onblur="alert('Hello');">Hello</p>
631 * @result alert('Hello');
639 * Bind a function to the load event of each matched element.
641 * @example $("p").load( function() { alert("Hello"); } );
642 * @before <p>Hello</p>
643 * @result <p onload="alert('Hello');">Hello</p>
647 * @param Function fn A function to bind to the load event on each of the matched elements.
652 * Bind a function to the select event of each matched element.
654 * @example $("p").select( function() { alert("Hello"); } );
655 * @before <p>Hello</p>
656 * @result <p onselect="alert('Hello');">Hello</p>
660 * @param Function fn A function to bind to the select event on each of the matched elements.
665 * Trigger the select event of each matched element. This causes all of the functions
666 * that have been bound to thet select event to be executed.
668 * @example $("p").select();
669 * @before <p onselect="alert('Hello');">Hello</p>
670 * @result alert('Hello');
678 * Bind a function to the mouseup event of each matched element.
680 * @example $("p").mouseup( function() { alert("Hello"); } );
681 * @before <p>Hello</p>
682 * @result <p onmouseup="alert('Hello');">Hello</p>
686 * @param Function fn A function to bind to the mouseup event on each of the matched elements.
691 * Bind a function to the unload event of each matched element.
693 * @example $("p").unload( function() { alert("Hello"); } );
694 * @before <p>Hello</p>
695 * @result <p onunload="alert('Hello');">Hello</p>
699 * @param Function fn A function to bind to the unload event on each of the matched elements.
704 * Bind a function to the change event of each matched element.
706 * @example $("p").change( function() { alert("Hello"); } );
707 * @before <p>Hello</p>
708 * @result <p onchange="alert('Hello');">Hello</p>
712 * @param Function fn A function to bind to the change event on each of the matched elements.
717 * Bind a function to the mouseout event of each matched element.
719 * @example $("p").mouseout( function() { alert("Hello"); } );
720 * @before <p>Hello</p>
721 * @result <p onmouseout="alert('Hello');">Hello</p>
725 * @param Function fn A function to bind to the mouseout event on each of the matched elements.
730 * Bind a function to the keyup event of each matched element.
732 * @example $("p").keyup( function() { alert("Hello"); } );
733 * @before <p>Hello</p>
734 * @result <p onkeyup="alert('Hello');">Hello</p>
738 * @param Function fn A function to bind to the keyup event on each of the matched elements.
743 * Bind a function to the click event of each matched element.
745 * @example $("p").click( function() { alert("Hello"); } );
746 * @before <p>Hello</p>
747 * @result <p onclick="alert('Hello');">Hello</p>
751 * @param Function fn A function to bind to the click event on each of the matched elements.
756 * Trigger the click event of each matched element. This causes all of the functions
757 * that have been bound to thet click event to be executed.
759 * @example $("p").click();
760 * @before <p onclick="alert('Hello');">Hello</p>
761 * @result alert('Hello');
769 * Bind a function to the resize event of each matched element.
771 * @example $("p").resize( function() { alert("Hello"); } );
772 * @before <p>Hello</p>
773 * @result <p onresize="alert('Hello');">Hello</p>
777 * @param Function fn A function to bind to the resize event on each of the matched elements.
782 * Bind a function to the mousemove event of each matched element.
784 * @example $("p").mousemove( function() { alert("Hello"); } );
785 * @before <p>Hello</p>
786 * @result <p onmousemove="alert('Hello');">Hello</p>
790 * @param Function fn A function to bind to the mousemove event on each of the matched elements.
795 * Bind a function to the mousedown event of each matched element.
797 * @example $("p").mousedown( function() { alert("Hello"); } );
798 * @before <p>Hello</p>
799 * @result <p onmousedown="alert('Hello');">Hello</p>
803 * @param Function fn A function to bind to the mousedown event on each of the matched elements.
808 * Bind a function to the mouseover event of each matched element.
810 * @example $("p").mouseover( function() { alert("Hello"); } );
811 * @before <p>Hello</p>
812 * @result <p onmouseover="alert('Hello');">Hello</p>
816 * @param Function fn A function to bind to the mousedown event on each of the matched elements.
819 jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
820 "mousedown,mouseup,mousemove,mouseover,mouseout,change,select," +
821 "submit,keydown,keypress,keyup,error").split(","), function(i,o){
823 // Handle event binding
824 jQuery.fn[o] = function(f){
825 return f ? this.bind(o, f) : this.trigger(o);
830 // If Mozilla is used
831 if ( jQuery.browser.mozilla || jQuery.browser.opera )
832 // Use the handy event callback
833 document.addEventListener( "DOMContentLoaded", jQuery.ready, false );
835 // If IE is used, use the excellent hack by Matthias Miller
836 // http://www.outofhanwell.com/blog/index.php?title=the_window_onload_problem_revisited
837 else if ( jQuery.browser.msie ) {
839 // Only works if you document.write() it
840 document.write("<scr" + "ipt id=__ie_init defer=true " +
841 "src=//:><\/script>");
843 // Use the defer script hack
844 var script = document.getElementById("__ie_init");
846 // script does not exist if jQuery is loaded dynamically
848 script.onreadystatechange = function() {
849 if ( this.readyState != "complete" ) return;
850 this.parentNode.removeChild( this );
858 } else if ( jQuery.browser.safari )
859 // Continually check to see if the document.readyState is valid
860 jQuery.safariTimer = setInterval(function(){
861 // loaded and complete are both valid states
862 if ( document.readyState == "loaded" ||
863 document.readyState == "complete" ) {
865 // If either one are found, remove the timer
866 clearInterval( jQuery.safariTimer );
867 jQuery.safariTimer = null;
869 // and execute any waiting functions
874 // A fallback to window.onload, that will always work
875 jQuery.event.add( window, "load", jQuery.ready );
879 // Clean up after IE to avoid memory leaks
880 if (jQuery.browser.msie)
881 jQuery(window).one("unload", function() {
882 var global = jQuery.event.global;
883 for ( var type in global ) {
884 var els = global[type], i = els.length;
885 if ( i && type != 'unload' )
887 jQuery.event.remove(els[i-1], type);