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 jQuery.each( this.global[type] || [], function(){
79 jQuery.event.trigger( type, data, this );
82 // Handle triggering a single element
84 var handler = element["on" + type ], val,
85 fn = jQuery.isFunction( element[ type ] );
88 // Pass along a fake event
89 data.unshift( this.fix({ type: type, target: element }) );
92 if ( (val = handler.apply( element, data )) !== false )
93 this.triggered = true;
96 if ( fn && val !== false )
99 this.triggered = false;
103 handle: function(event) {
104 // Handle the second event of a trigger and when
105 // an event is called after a page has unloaded
106 if ( typeof jQuery == "undefined" || jQuery.event.triggered ) return;
108 // Empty object is for triggered events with no data
109 event = jQuery.event.fix( event || window.event || {} );
111 // returned undefined or false
114 var c = this.events[event.type];
116 var args = [].slice.call( arguments, 1 );
117 args.unshift( event );
120 // Pass in a reference to the handler function itself
121 // So that we can later remove it
122 args[0].handler = c[j];
123 args[0].data = c[j].data;
125 if ( c[j].apply( this, args ) === false ) {
126 event.preventDefault();
127 event.stopPropagation();
132 // Clean up added properties in IE to prevent memory leak
133 if (jQuery.browser.msie) event.target = event.preventDefault = event.stopPropagation = event.handler = event.data = null;
138 fix: function(event) {
139 // Fix target property, if necessary
140 if ( !event.target && event.srcElement )
141 event.target = event.srcElement;
143 // Calculate pageX/Y if missing and clientX/Y available
144 if ( event.pageX == undefined && event.clientX != undefined ) {
145 var e = document.documentElement, b = document.body;
146 event.pageX = event.clientX + (e.scrollLeft || b.scrollLeft);
147 event.pageY = event.clientY + (e.scrollTop || b.scrollTop);
150 // check if target is a textnode (safari)
151 if (jQuery.browser.safari && event.target.nodeType == 3) {
152 // store a copy of the original event object
153 // and clone because target is read only
154 var originalEvent = event;
155 event = jQuery.extend({}, originalEvent);
157 // get parentnode from textnode
158 event.target = originalEvent.target.parentNode;
160 // add preventDefault and stopPropagation since
161 // they will not work on the clone
162 event.preventDefault = function() {
163 return originalEvent.preventDefault();
165 event.stopPropagation = function() {
166 return originalEvent.stopPropagation();
170 // fix preventDefault and stopPropagation
171 if (!event.preventDefault)
172 event.preventDefault = function() {
173 this.returnValue = false;
176 if (!event.stopPropagation)
177 event.stopPropagation = function() {
178 this.cancelBubble = true;
188 * Binds a handler to a particular event (like click) for each matched element.
189 * The event handler is passed an event object that you can use to prevent
190 * default behaviour. To stop both default action and event bubbling, your handler
191 * has to return false.
193 * In most cases, you can define your event handlers as anonymous functions
194 * (see first example). In cases where that is not possible, you can pass additional
195 * data as the second paramter (and the handler function as the third), see
198 * @example $("p").bind("click", function(){
199 * alert( $(this).text() );
201 * @before <p>Hello</p>
202 * @result alert("Hello")
204 * @example function handler(event) {
205 * alert(event.data.foo);
207 * $("p").bind("click", {foo: "bar"}, handler)
208 * @result alert("bar")
209 * @desc Pass some additional data to the event handler.
211 * @example $("form").bind("submit", function() { return false; })
212 * @desc Cancel a default action and prevent it from bubbling by returning false
213 * from your function.
215 * @example $("form").bind("submit", function(event){
216 * event.preventDefault();
218 * @desc Cancel only the default action by using the preventDefault method.
221 * @example $("form").bind("submit", function(event){
222 * event.stopPropagation();
224 * @desc Stop only an event from bubbling by using the stopPropagation method.
228 * @param String type An event type
229 * @param Object data (optional) Additional data passed to the event handler as event.data
230 * @param Function fn A function to bind to the event on each of the set of matched elements
233 bind: function( type, data, fn ) {
234 return this.each(function(){
235 jQuery.event.add( this, type, fn || data, data );
240 * Binds a handler to a particular event (like click) for each matched element.
241 * The handler is executed only once for each element. Otherwise, the same rules
242 * as described in bind() apply.
243 The event handler is passed an event object that you can use to prevent
244 * default behaviour. To stop both default action and event bubbling, your handler
245 * has to return false.
247 * In most cases, you can define your event handlers as anonymous functions
248 * (see first example). In cases where that is not possible, you can pass additional
249 * data as the second paramter (and the handler function as the third), see
252 * @example $("p").one("click", function(){
253 * alert( $(this).text() );
255 * @before <p>Hello</p>
256 * @result alert("Hello")
260 * @param String type An event type
261 * @param Object data (optional) Additional data passed to the event handler as event.data
262 * @param Function fn A function to bind to the event on each of the set of matched elements
265 one: function( type, data, fn ) {
266 return this.each(function(){
267 jQuery.event.add( this, type, function(event) {
268 jQuery(this).unbind(event);
269 return (fn || data).apply( this, arguments);
275 * The opposite of bind, removes a bound event from each of the matched
278 * Without any arguments, all bound events are removed.
280 * If the type is provided, all bound events of that type are removed.
282 * If the function that was passed to bind is provided as the second argument,
283 * only that specific event handler is removed.
285 * @example $("p").unbind()
286 * @before <p onclick="alert('Hello');">Hello</p>
287 * @result [ <p>Hello</p> ]
289 * @example $("p").unbind( "click" )
290 * @before <p onclick="alert('Hello');">Hello</p>
291 * @result [ <p>Hello</p> ]
293 * @example $("p").unbind( "click", function() { alert("Hello"); } )
294 * @before <p onclick="alert('Hello');">Hello</p>
295 * @result [ <p>Hello</p> ]
299 * @param String type (optional) An event type
300 * @param Function fn (optional) A function to unbind from the event on each of the set of matched elements
303 unbind: function( type, fn ) {
304 return this.each(function(){
305 jQuery.event.remove( this, type, fn );
310 * Trigger a type of event on every matched element.
312 * @example $("p").trigger("click")
313 * @before <p click="alert('hello')">Hello</p>
314 * @result alert('hello')
318 * @param String type An event type to trigger.
321 trigger: function( type, data ) {
322 return this.each(function(){
323 jQuery.event.trigger( type, data, this );
328 * Toggle between two function calls every other click.
329 * Whenever a matched element is clicked, the first specified function
330 * is fired, when clicked again, the second is fired. All subsequent
331 * clicks continue to rotate through the two functions.
333 * Use unbind("click") to remove.
335 * @example $("p").toggle(function(){
336 * $(this).addClass("selected");
338 * $(this).removeClass("selected");
343 * @param Function even The function to execute on every even click.
344 * @param Function odd The function to execute on every odd click.
348 // Save reference to arguments for access in closure
351 return this.click(function(e) {
352 // Figure out which function to execute
353 this.lastToggle = this.lastToggle == 0 ? 1 : 0;
355 // Make sure that clicks stop
358 // and execute the function
359 return a[this.lastToggle].apply( this, [e] ) || false;
364 * A method for simulating hovering (moving the mouse on, and off,
365 * an object). This is a custom method which provides an 'in' to a
368 * Whenever the mouse cursor is moved over a matched
369 * element, the first specified function is fired. Whenever the mouse
370 * moves off of the element, the second specified function fires.
371 * Additionally, checks are in place to see if the mouse is still within
372 * the specified element itself (for example, an image inside of a div),
373 * and if it is, it will continue to 'hover', and not move out
374 * (a common error in using a mouseout event handler).
376 * @example $("p").hover(function(){
377 * $(this).addClass("over");
379 * $(this).addClass("out");
384 * @param Function over The function to fire whenever the mouse is moved over a matched element.
385 * @param Function out The function to fire whenever the mouse is moved off of a matched element.
388 hover: function(f,g) {
390 // A private function for handling mouse 'hovering'
391 function handleHover(e) {
392 // Check if mouse(over|out) are still within the same parent element
393 var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
395 // Traverse up the tree
396 while ( p && p != this ) try { p = p.parentNode } catch(e) { p = this; };
398 // If we actually just moused on to a sub-element, ignore it
399 if ( p == this ) return false;
401 // Execute the right function
402 return (e.type == "mouseover" ? f : g).apply(this, [e]);
405 // Bind the function to the two event listeners
406 return this.mouseover(handleHover).mouseout(handleHover);
410 * Bind a function to be executed whenever the DOM is ready to be
411 * traversed and manipulated. This is probably the most important
412 * function included in the event module, as it can greatly improve
413 * the response times of your web applications.
415 * In a nutshell, this is a solid replacement for using window.onload,
416 * and attaching a function to that. By using this method, your bound Function
417 * will be called the instant the DOM is ready to be read and manipulated,
418 * which is exactly what 99.99% of all Javascript code needs to run.
420 * There is one argument passed to the ready event handler: A reference to
421 * the jQuery function. You can name that argument whatever you like, and
422 * can therefore stick with the $ alias without risc of naming collisions.
424 * Please ensure you have no code in your <body> onload event handler,
425 * otherwise $(document).ready() may not fire.
427 * You can have as many $(document).ready events on your page as you like.
428 * The functions are then executed in the order they were added.
430 * @example $(document).ready(function(){ Your code here... });
432 * @example jQuery(function($) {
433 * // Your code using failsafe $ alias here...
435 * @desc Uses both the shortcut for $(document).ready() and the argument
436 * to write failsafe jQuery code using the $ alias, without relying on the
441 * @param Function fn The function to be executed when the DOM is ready.
443 * @see $.noConflict()
447 // If the DOM is already ready
448 if ( jQuery.isReady )
449 // Execute the function immediately
450 f.apply( document, [jQuery] );
452 // Otherwise, remember the function for later
454 // Add the function to the wait list
455 jQuery.readyList.push( function() { return f.apply(this, [jQuery]) } );
464 * All the code that makes DOM Ready work nicely.
469 // Handle when the DOM is ready
471 // Make sure that the DOM is not already loaded
472 if ( !jQuery.isReady ) {
473 // Remember that the DOM is ready
474 jQuery.isReady = true;
476 // If there are functions bound, to execute
477 if ( jQuery.readyList ) {
478 // Execute all of them
479 jQuery.each( jQuery.readyList, function(){
480 this.apply( document );
483 // Reset the list of functions
484 jQuery.readyList = null;
486 // Remove event lisenter to avoid memory leak
487 if ( jQuery.browser.mozilla || jQuery.browser.opera )
488 document.removeEventListener( "DOMContentLoaded", jQuery.ready, false );
496 * Bind a function to the scroll event of each matched element.
498 * @example $("p").scroll( function() { alert("Hello"); } );
499 * @before <p>Hello</p>
500 * @result <p onscroll="alert('Hello');">Hello</p>
504 * @param Function fn A function to bind to the scroll event on each of the matched elements.
509 * Bind a function to the submit event of each matched element.
511 * @example $("#myform").submit( function() {
512 * return $("input", this).val().length > 0;
514 * @before <form id="myform"><input /></form>
515 * @desc Prevents the form submission when the input has no value entered.
519 * @param Function fn A function to bind to the submit event on each of the matched elements.
524 * Trigger the submit event of each matched element. This causes all of the functions
525 * that have been bound to thet submit event to be executed.
527 * Note: This does not execute the submit method of the form element! If you need to
528 * submit the form via code, you have to use the DOM method, eg. $("form")[0].submit();
530 * @example $("form").submit();
531 * @desc Triggers all submit events registered for forms, but does not submit the form
539 * Bind a function to the focus event of each matched element.
541 * @example $("p").focus( function() { alert("Hello"); } );
542 * @before <p>Hello</p>
543 * @result <p onfocus="alert('Hello');">Hello</p>
547 * @param Function fn A function to bind to the focus event on each of the matched elements.
552 * Trigger the focus event of each matched element. This causes all of the functions
553 * that have been bound to thet focus event to be executed.
555 * Note: This does not execute the focus method of the underlying elements! If you need to
556 * focus an element via code, you have to use the DOM method, eg. $("#myinput")[0].focus();
558 * @example $("p").focus();
559 * @before <p onfocus="alert('Hello');">Hello</p>
560 * @result alert('Hello');
568 * Bind a function to the keydown event of each matched element.
570 * @example $("p").keydown( function() { alert("Hello"); } );
571 * @before <p>Hello</p>
572 * @result <p onkeydown="alert('Hello');">Hello</p>
576 * @param Function fn A function to bind to the keydown event on each of the matched elements.
581 * Bind a function to the dblclick event of each matched element.
583 * @example $("p").dblclick( function() { alert("Hello"); } );
584 * @before <p>Hello</p>
585 * @result <p ondblclick="alert('Hello');">Hello</p>
589 * @param Function fn A function to bind to the dblclick event on each of the matched elements.
594 * Bind a function to the keypress event of each matched element.
596 * @example $("p").keypress( function() { alert("Hello"); } );
597 * @before <p>Hello</p>
598 * @result <p onkeypress="alert('Hello');">Hello</p>
602 * @param Function fn A function to bind to the keypress event on each of the matched elements.
607 * Bind a function to the error event of each matched element.
609 * @example $("p").error( function() { alert("Hello"); } );
610 * @before <p>Hello</p>
611 * @result <p onerror="alert('Hello');">Hello</p>
615 * @param Function fn A function to bind to the error event on each of the matched elements.
620 * Bind a function to the blur event of each matched element.
622 * @example $("p").blur( function() { alert("Hello"); } );
623 * @before <p>Hello</p>
624 * @result <p onblur="alert('Hello');">Hello</p>
628 * @param Function fn A function to bind to the blur event on each of the matched elements.
633 * Trigger the blur event of each matched element. This causes all of the functions
634 * that have been bound to thet blur event to be executed.
636 * Note: This does not execute the blur method of the underlying elements! If you need to
637 * blur an element via code, you have to use the DOM method, eg. $("#myinput")[0].blur();
639 * @example $("p").blur();
640 * @before <p onblur="alert('Hello');">Hello</p>
641 * @result alert('Hello');
649 * Bind a function to the load event of each matched element.
651 * @example $("p").load( function() { alert("Hello"); } );
652 * @before <p>Hello</p>
653 * @result <p onload="alert('Hello');">Hello</p>
657 * @param Function fn A function to bind to the load event on each of the matched elements.
662 * Bind a function to the select event of each matched element.
664 * @example $("p").select( function() { alert("Hello"); } );
665 * @before <p>Hello</p>
666 * @result <p onselect="alert('Hello');">Hello</p>
670 * @param Function fn A function to bind to the select event on each of the matched elements.
675 * Trigger the select event of each matched element. This causes all of the functions
676 * that have been bound to thet select event to be executed.
678 * @example $("p").select();
679 * @before <p onselect="alert('Hello');">Hello</p>
680 * @result alert('Hello');
688 * Bind a function to the mouseup event of each matched element.
690 * @example $("p").mouseup( function() { alert("Hello"); } );
691 * @before <p>Hello</p>
692 * @result <p onmouseup="alert('Hello');">Hello</p>
696 * @param Function fn A function to bind to the mouseup event on each of the matched elements.
701 * Bind a function to the unload event of each matched element.
703 * @example $("p").unload( function() { alert("Hello"); } );
704 * @before <p>Hello</p>
705 * @result <p onunload="alert('Hello');">Hello</p>
709 * @param Function fn A function to bind to the unload event on each of the matched elements.
714 * Bind a function to the change event of each matched element.
716 * @example $("p").change( function() { alert("Hello"); } );
717 * @before <p>Hello</p>
718 * @result <p onchange="alert('Hello');">Hello</p>
722 * @param Function fn A function to bind to the change event on each of the matched elements.
727 * Bind a function to the mouseout event of each matched element.
729 * @example $("p").mouseout( function() { alert("Hello"); } );
730 * @before <p>Hello</p>
731 * @result <p onmouseout="alert('Hello');">Hello</p>
735 * @param Function fn A function to bind to the mouseout event on each of the matched elements.
740 * Bind a function to the keyup event of each matched element.
742 * @example $("p").keyup( function() { alert("Hello"); } );
743 * @before <p>Hello</p>
744 * @result <p onkeyup="alert('Hello');">Hello</p>
748 * @param Function fn A function to bind to the keyup event on each of the matched elements.
753 * Bind a function to the click event of each matched element.
755 * @example $("p").click( function() { alert("Hello"); } );
756 * @before <p>Hello</p>
757 * @result <p onclick="alert('Hello');">Hello</p>
761 * @param Function fn A function to bind to the click event on each of the matched elements.
766 * Trigger the click event of each matched element. This causes all of the functions
767 * that have been bound to thet click event to be executed.
769 * @example $("p").click();
770 * @before <p onclick="alert('Hello');">Hello</p>
771 * @result alert('Hello');
779 * Bind a function to the resize event of each matched element.
781 * @example $("p").resize( function() { alert("Hello"); } );
782 * @before <p>Hello</p>
783 * @result <p onresize="alert('Hello');">Hello</p>
787 * @param Function fn A function to bind to the resize event on each of the matched elements.
792 * Bind a function to the mousemove event of each matched element.
794 * @example $("p").mousemove( function() { alert("Hello"); } );
795 * @before <p>Hello</p>
796 * @result <p onmousemove="alert('Hello');">Hello</p>
800 * @param Function fn A function to bind to the mousemove event on each of the matched elements.
805 * Bind a function to the mousedown event of each matched element.
807 * @example $("p").mousedown( function() { alert("Hello"); } );
808 * @before <p>Hello</p>
809 * @result <p onmousedown="alert('Hello');">Hello</p>
813 * @param Function fn A function to bind to the mousedown event on each of the matched elements.
818 * Bind a function to the mouseover event of each matched element.
820 * @example $("p").mouseover( function() { alert("Hello"); } );
821 * @before <p>Hello</p>
822 * @result <p onmouseover="alert('Hello');">Hello</p>
826 * @param Function fn A function to bind to the mousedown event on each of the matched elements.
829 jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
830 "mousedown,mouseup,mousemove,mouseover,mouseout,change,select," +
831 "submit,keydown,keypress,keyup,error").split(","), function(i,o){
833 // Handle event binding
834 jQuery.fn[o] = function(f){
835 return f ? this.bind(o, f) : this.trigger(o);
840 // If Mozilla is used
841 if ( jQuery.browser.mozilla || jQuery.browser.opera )
842 // Use the handy event callback
843 document.addEventListener( "DOMContentLoaded", jQuery.ready, false );
845 // If IE is used, use the excellent hack by Matthias Miller
846 // http://www.outofhanwell.com/blog/index.php?title=the_window_onload_problem_revisited
847 else if ( jQuery.browser.msie ) {
849 // Only works if you document.write() it
850 document.write("<scr" + "ipt id=__ie_init defer=true " +
851 "src=//:><\/script>");
853 // Use the defer script hack
854 var script = document.getElementById("__ie_init");
856 // script does not exist if jQuery is loaded dynamically
858 script.onreadystatechange = function() {
859 if ( this.readyState != "complete" ) return;
860 this.parentNode.removeChild( this );
868 } else if ( jQuery.browser.safari )
869 // Continually check to see if the document.readyState is valid
870 jQuery.safariTimer = setInterval(function(){
871 // loaded and complete are both valid states
872 if ( document.readyState == "loaded" ||
873 document.readyState == "complete" ) {
875 // If either one are found, remove the timer
876 clearInterval( jQuery.safariTimer );
877 jQuery.safariTimer = null;
879 // and execute any waiting functions
884 // A fallback to window.onload, that will always work
885 jQuery.event.add( window, "load", jQuery.ready );
889 // Clean up after IE to avoid memory leaks
890 if (jQuery.browser.msie)
891 jQuery(window).one("unload", function() {
892 var global = jQuery.event.global;
893 for ( var type in global ) {
894 var els = global[type], i = els.length;
895 if ( i && type != 'unload' )
897 jQuery.event.remove(els[i-1], type);