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
83 else if ( element["on" + type] ) {
84 // Pass along a fake event
85 data.unshift( this.fix({ type: type, target: element }) );
88 var val = element["on" + type].apply( element, data );
90 if ( val !== false && jQuery.isFunction( element[ type ] ) )
95 handle: function(event) {
96 if ( typeof jQuery == "undefined" ) return false;
98 // Empty object is for triggered events with no data
99 event = jQuery.event.fix( event || window.event || {} );
101 // returned undefined or false
104 var c = this.events[event.type];
106 var args = [].slice.call( arguments, 1 );
107 args.unshift( event );
110 // Pass in a reference to the handler function itself
111 // So that we can later remove it
112 args[0].handler = c[j];
113 args[0].data = c[j].data;
115 if ( c[j].apply( this, args ) === false ) {
116 event.preventDefault();
117 event.stopPropagation();
122 // Clean up added properties in IE to prevent memory leak
123 if (jQuery.browser.msie) event.target = event.preventDefault = event.stopPropagation = event.handler = event.data = null;
128 fix: function(event) {
129 // Fix target property, if necessary
130 if ( !event.target && event.srcElement )
131 event.target = event.srcElement;
133 // Calculate pageX/Y if missing and clientX/Y available
134 if ( event.pageX == undefined && event.clientX != undefined ) {
135 var e = document.documentElement, b = document.body;
136 event.pageX = event.clientX + (e.scrollLeft || b.scrollLeft);
137 event.pageY = event.clientY + (e.scrollTop || b.scrollTop);
140 // check if target is a textnode (safari)
141 if (jQuery.browser.safari && event.target.nodeType == 3) {
142 // store a copy of the original event object
143 // and clone because target is read only
144 var originalEvent = event;
145 event = jQuery.extend({}, originalEvent);
147 // get parentnode from textnode
148 event.target = originalEvent.target.parentNode;
150 // add preventDefault and stopPropagation since
151 // they will not work on the clone
152 event.preventDefault = function() {
153 return originalEvent.preventDefault();
155 event.stopPropagation = function() {
156 return originalEvent.stopPropagation();
160 // fix preventDefault and stopPropagation
161 if (!event.preventDefault)
162 event.preventDefault = function() {
163 this.returnValue = false;
166 if (!event.stopPropagation)
167 event.stopPropagation = function() {
168 this.cancelBubble = true;
178 * Binds a handler to a particular event (like click) for each matched element.
179 * The event handler is passed an event object that you can use to prevent
180 * default behaviour. To stop both default action and event bubbling, your handler
181 * has to return false.
183 * In most cases, you can define your event handlers as anonymous functions
184 * (see first example). In cases where that is not possible, you can pass additional
185 * data as the second paramter (and the handler function as the third), see
188 * @example $("p").bind("click", function(){
189 * alert( $(this).text() );
191 * @before <p>Hello</p>
192 * @result alert("Hello")
194 * @example function handler(event) {
195 * alert(event.data.foo);
197 * $("p").bind("click", {foo: "bar"}, handler)
198 * @result alert("bar")
199 * @desc Pass some additional data to the event handler.
201 * @example $("form").bind("submit", function() { return false; })
202 * @desc Cancel a default action and prevent it from bubbling by returning false
203 * from your function.
205 * @example $("form").bind("submit", function(event){
206 * event.preventDefault();
208 * @desc Cancel only the default action by using the preventDefault method.
211 * @example $("form").bind("submit", function(event){
212 * event.stopPropagation();
214 * @desc Stop only an event from bubbling by using the stopPropagation method.
218 * @param String type An event type
219 * @param Object data (optional) Additional data passed to the event handler as event.data
220 * @param Function fn A function to bind to the event on each of the set of matched elements
223 bind: function( type, data, fn ) {
224 return this.each(function(){
225 jQuery.event.add( this, type, fn || data, data );
230 * Binds a handler to a particular event (like click) for each matched element.
231 * The handler is executed only once for each element. Otherwise, the same rules
232 * as described in bind() apply.
233 The event handler is passed an event object that you can use to prevent
234 * default behaviour. To stop both default action and event bubbling, your handler
235 * has to return false.
237 * In most cases, you can define your event handlers as anonymous functions
238 * (see first example). In cases where that is not possible, you can pass additional
239 * data as the second paramter (and the handler function as the third), see
242 * @example $("p").one("click", function(){
243 * alert( $(this).text() );
245 * @before <p>Hello</p>
246 * @result alert("Hello")
250 * @param String type An event type
251 * @param Object data (optional) Additional data passed to the event handler as event.data
252 * @param Function fn A function to bind to the event on each of the set of matched elements
255 one: function( type, data, fn ) {
256 return this.each(function(){
257 jQuery.event.add( this, type, function(event) {
258 jQuery(this).unbind(event);
259 return (fn || data).apply( this, arguments);
265 * The opposite of bind, removes a bound event from each of the matched
268 * Without any arguments, all bound events are removed.
270 * If the type is provided, all bound events of that type are removed.
272 * If the function that was passed to bind is provided as the second argument,
273 * only that specific event handler is removed.
275 * @example $("p").unbind()
276 * @before <p onclick="alert('Hello');">Hello</p>
277 * @result [ <p>Hello</p> ]
279 * @example $("p").unbind( "click" )
280 * @before <p onclick="alert('Hello');">Hello</p>
281 * @result [ <p>Hello</p> ]
283 * @example $("p").unbind( "click", function() { alert("Hello"); } )
284 * @before <p onclick="alert('Hello');">Hello</p>
285 * @result [ <p>Hello</p> ]
289 * @param String type (optional) An event type
290 * @param Function fn (optional) A function to unbind from the event on each of the set of matched elements
293 unbind: function( type, fn ) {
294 return this.each(function(){
295 jQuery.event.remove( this, type, fn );
300 * Trigger a type of event on every matched element.
302 * @example $("p").trigger("click")
303 * @before <p click="alert('hello')">Hello</p>
304 * @result alert('hello')
308 * @param String type An event type to trigger.
311 trigger: function( type, data ) {
312 return this.each(function(){
313 jQuery.event.trigger( type, data, this );
318 * Toggle between two function calls every other click.
319 * Whenever a matched element is clicked, the first specified function
320 * is fired, when clicked again, the second is fired. All subsequent
321 * clicks continue to rotate through the two functions.
323 * Use unbind("click") to remove.
325 * @example $("p").toggle(function(){
326 * $(this).addClass("selected");
328 * $(this).removeClass("selected");
333 * @param Function even The function to execute on every even click.
334 * @param Function odd The function to execute on every odd click.
338 // Save reference to arguments for access in closure
341 return this.click(function(e) {
342 // Figure out which function to execute
343 this.lastToggle = this.lastToggle == 0 ? 1 : 0;
345 // Make sure that clicks stop
348 // and execute the function
349 return a[this.lastToggle].apply( this, [e] ) || false;
354 * A method for simulating hovering (moving the mouse on, and off,
355 * an object). This is a custom method which provides an 'in' to a
358 * Whenever the mouse cursor is moved over a matched
359 * element, the first specified function is fired. Whenever the mouse
360 * moves off of the element, the second specified function fires.
361 * Additionally, checks are in place to see if the mouse is still within
362 * the specified element itself (for example, an image inside of a div),
363 * and if it is, it will continue to 'hover', and not move out
364 * (a common error in using a mouseout event handler).
366 * @example $("p").hover(function(){
367 * $(this).addClass("over");
369 * $(this).addClass("out");
374 * @param Function over The function to fire whenever the mouse is moved over a matched element.
375 * @param Function out The function to fire whenever the mouse is moved off of a matched element.
378 hover: function(f,g) {
380 // A private function for handling mouse 'hovering'
381 function handleHover(e) {
382 // Check if mouse(over|out) are still within the same parent element
383 var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
385 // Traverse up the tree
386 while ( p && p != this ) try { p = p.parentNode } catch(e) { p = this; };
388 // If we actually just moused on to a sub-element, ignore it
389 if ( p == this ) return false;
391 // Execute the right function
392 return (e.type == "mouseover" ? f : g).apply(this, [e]);
395 // Bind the function to the two event listeners
396 return this.mouseover(handleHover).mouseout(handleHover);
400 * Bind a function to be executed whenever the DOM is ready to be
401 * traversed and manipulated. This is probably the most important
402 * function included in the event module, as it can greatly improve
403 * the response times of your web applications.
405 * In a nutshell, this is a solid replacement for using window.onload,
406 * and attaching a function to that. By using this method, your bound Function
407 * will be called the instant the DOM is ready to be read and manipulated,
408 * which is exactly what 99.99% of all Javascript code needs to run.
410 * There is one argument passed to the ready event handler: A reference to
411 * the jQuery function. You can name that argument whatever you like, and
412 * can therefore stick with the $ alias without risc of naming collisions.
414 * Please ensure you have no code in your <body> onload event handler,
415 * otherwise $(document).ready() may not fire.
417 * You can have as many $(document).ready events on your page as you like.
418 * The functions are then executed in the order they were added.
420 * @example $(document).ready(function(){ Your code here... });
422 * @example jQuery(function($) {
423 * // Your code using failsafe $ alias here...
425 * @desc Uses both the shortcut for $(document).ready() and the argument
426 * to write failsafe jQuery code using the $ alias, without relying on the
431 * @param Function fn The function to be executed when the DOM is ready.
433 * @see $.noConflict()
437 // If the DOM is already ready
438 if ( jQuery.isReady )
439 // Execute the function immediately
440 f.apply( document, [jQuery] );
442 // Otherwise, remember the function for later
444 // Add the function to the wait list
445 jQuery.readyList.push( function() { return f.apply(this, [jQuery]) } );
454 * All the code that makes DOM Ready work nicely.
459 // Handle when the DOM is ready
461 // Make sure that the DOM is not already loaded
462 if ( !jQuery.isReady ) {
463 // Remember that the DOM is ready
464 jQuery.isReady = true;
466 // If there are functions bound, to execute
467 if ( jQuery.readyList ) {
468 // Execute all of them
469 jQuery.each( jQuery.readyList, function(){
470 this.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);