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 if ( element[ type ] && element[ type ].constructor == Function )
88 // Pass along a fake event
89 data.unshift( this.fix({ type: type, target: element }) );
92 element["on" + type].apply( element, data );
97 handle: function(event) {
98 if ( typeof jQuery == "undefined" ) return false;
100 // Empty object is for triggered events with no data
101 event = jQuery.event.fix( event || window.event || {} );
103 // returned undefined or false
106 var c = this.events[event.type];
108 var args = [].slice.call( arguments, 1 );
109 args.unshift( event );
112 // Pass in a reference to the handler function itself
113 // So that we can later remove it
114 args[0].handler = c[j];
115 args[0].data = c[j].data;
117 if ( c[j].apply( this, args ) === false ) {
118 event.preventDefault();
119 event.stopPropagation();
124 // Clean up added properties in IE to prevent memory leak
125 if (jQuery.browser.msie) event.target = event.preventDefault = event.stopPropagation = event.handler = event.data = null;
130 fix: function(event) {
131 // Fix target property, if necessary
132 if ( !event.target && event.srcElement )
133 event.target = event.srcElement;
135 // Calculate pageX/Y if missing and clientX/Y available
136 if ( typeof event.pageX == "undefined" && typeof event.clientX != "undefined" ) {
137 var e = document.documentElement, b = document.body;
138 event.pageX = event.clientX + (e.scrollLeft || b.scrollLeft);
139 event.pageY = event.clientY + (e.scrollTop || b.scrollTop);
142 // check if target is a textnode (safari)
143 if (jQuery.browser.safari && event.target.nodeType == 3) {
144 // store a copy of the original event object
145 // and clone because target is read only
146 var originalEvent = event;
147 event = jQuery.extend({}, originalEvent);
149 // get parentnode from textnode
150 event.target = originalEvent.target.parentNode;
152 // add preventDefault and stopPropagation since
153 // they will not work on the clone
154 event.preventDefault = function() {
155 return originalEvent.preventDefault();
157 event.stopPropagation = function() {
158 return originalEvent.stopPropagation();
162 // fix preventDefault and stopPropagation
163 if (!event.preventDefault)
164 event.preventDefault = function() {
165 this.returnValue = false;
168 if (!event.stopPropagation)
169 event.stopPropagation = function() {
170 this.cancelBubble = true;
180 * Binds a handler to a particular event (like click) for each matched element.
181 * The event handler is passed an event object that you can use to prevent
182 * default behaviour. To stop both default action and event bubbling, your handler
183 * has to return false.
185 * In most cases, you can define your event handlers as anonymous functions
186 * (see first example). In cases where that is not possible, you can pass additional
187 * data as the second paramter (and the handler function as the third), see
190 * @example $("p").bind( "click", function() {
191 * alert( $(this).text() );
193 * @before <p>Hello</p>
194 * @result alert("Hello")
196 * @example var handler = function(event) {
197 * alert(event.data.foo);
199 * $("p").bind( "click", {foo: "bar"}, handler)
200 * @result alert("bar")
201 * @desc Pass some additional data to the event handler.
203 * @example $("form").bind( "submit", function() { return false; } )
204 * @desc Cancel a default action and prevent it from bubbling by returning false
205 * from your function.
207 * @example $("form").bind( "submit", function(event) {
208 * event.preventDefault();
210 * @desc Cancel only the default action by using the preventDefault method.
213 * @example $("form").bind( "submit", function(event) {
214 * event.stopPropagation();
216 * @desc Stop only an event from bubbling by using the stopPropagation method.
220 * @param String type An event type
221 * @param Object data (optional) Additional data passed to the event handler as event.data
222 * @param Function fn A function to bind to the event on each of the set of matched elements
225 bind: function( type, data, fn ) {
226 return this.each(function(){
227 jQuery.event.add( this, type, fn || data, data );
232 * Binds a handler to a particular event (like click) for each matched element.
233 * The handler is executed only once for each element. Otherwise, the same rules
234 * as described in bind() apply.
235 The event handler is passed an event object that you can use to prevent
236 * default behaviour. To stop both default action and event bubbling, your handler
237 * has to return false.
239 * In most cases, you can define your event handlers as anonymous functions
240 * (see first example). In cases where that is not possible, you can pass additional
241 * data as the second paramter (and the handler function as the third), see
244 * @example $("p").one( "click", function() {
245 * alert( $(this).text() );
247 * @before <p>Hello</p>
248 * @result alert("Hello")
252 * @param String type An event type
253 * @param Object data (optional) Additional data passed to the event handler as event.data
254 * @param Function fn A function to bind to the event on each of the set of matched elements
257 one: function( type, data, fn ) {
258 return this.each(function(){
259 jQuery.event.add( this, type, function(event) {
260 jQuery(this).unbind(event);
261 return (fn || data).apply( this, arguments);
267 * The opposite of bind, removes a bound event from each of the matched
270 * Without any arguments, all bound events are removed.
272 * If the type is provided, all bound events of that type are removed.
274 * If the function that was passed to bind is provided as the second argument,
275 * only that specific event handler is removed.
277 * @example $("p").unbind()
278 * @before <p onclick="alert('Hello');">Hello</p>
279 * @result [ <p>Hello</p> ]
281 * @example $("p").unbind( "click" )
282 * @before <p onclick="alert('Hello');">Hello</p>
283 * @result [ <p>Hello</p> ]
285 * @example $("p").unbind( "click", function() { alert("Hello"); } )
286 * @before <p onclick="alert('Hello');">Hello</p>
287 * @result [ <p>Hello</p> ]
291 * @param String type (optional) An event type
292 * @param Function fn (optional) A function to unbind from the event on each of the set of matched elements
295 unbind: function( type, fn ) {
296 return this.each(function(){
297 jQuery.event.remove( this, type, fn );
302 * Trigger a type of event on every matched element.
304 * @example $("p").trigger("click")
305 * @before <p click="alert('hello')">Hello</p>
306 * @result alert('hello')
310 * @param String type An event type to trigger.
313 trigger: function( type, data ) {
314 return this.each(function(){
315 jQuery.event.trigger( type, data, this );
319 // We're overriding the old toggle function, so
320 // remember it for later
321 _toggle: jQuery.fn.toggle,
324 * Toggle between two function calls every other click.
325 * Whenever a matched element is clicked, the first specified function
326 * is fired, when clicked again, the second is fired. All subsequent
327 * clicks continue to rotate through the two functions.
329 * Use unbind("click") to remove.
331 * @example $("p").toggle(function(){
332 * $(this).addClass("selected");
334 * $(this).removeClass("selected");
339 * @param Function even The function to execute on every even click.
340 * @param Function odd The function to execute on every odd click.
344 // save reference to arguments for access in closure
346 return typeof a[0] == "function" && typeof a[1] == "function" ? this.click(function(e) {
347 // Figure out which function to execute
348 this.lastToggle = this.lastToggle == 0 ? 1 : 0;
350 // Make sure that clicks stop
353 // and execute the function
354 return a[this.lastToggle].apply( this, [e] ) || false;
357 // Otherwise, execute the old toggle function
358 this._toggle.apply( this, arguments );
362 * A method for simulating hovering (moving the mouse on, and off,
363 * an object). This is a custom method which provides an 'in' to a
366 * Whenever the mouse cursor is moved over a matched
367 * element, the first specified function is fired. Whenever the mouse
368 * moves off of the element, the second specified function fires.
369 * Additionally, checks are in place to see if the mouse is still within
370 * the specified element itself (for example, an image inside of a div),
371 * and if it is, it will continue to 'hover', and not move out
372 * (a common error in using a mouseout event handler).
374 * @example $("p").hover(function(){
375 * $(this).addClass("over");
377 * $(this).addClass("out");
382 * @param Function over The function to fire whenever the mouse is moved over a matched element.
383 * @param Function out The function to fire whenever the mouse is moved off of a matched element.
386 hover: function(f,g) {
388 // A private function for handling mouse 'hovering'
389 function handleHover(e) {
390 // Check if mouse(over|out) are still within the same parent element
391 var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
393 // Traverse up the tree
394 while ( p && p != this ) try { p = p.parentNode } catch(e) { p = this; };
396 // If we actually just moused on to a sub-element, ignore it
397 if ( p == this ) return false;
399 // Execute the right function
400 return (e.type == "mouseover" ? f : g).apply(this, [e]);
403 // Bind the function to the two event listeners
404 return this.mouseover(handleHover).mouseout(handleHover);
408 * Bind a function to be executed whenever the DOM is ready to be
409 * traversed and manipulated. This is probably the most important
410 * function included in the event module, as it can greatly improve
411 * the response times of your web applications.
413 * In a nutshell, this is a solid replacement for using window.onload,
414 * and attaching a function to that. By using this method, your bound Function
415 * will be called the instant the DOM is ready to be read and manipulated,
416 * which is exactly what 99.99% of all Javascript code needs to run.
418 * Please ensure you have no code in your <body> onload event handler,
419 * otherwise $(document).ready() may not fire.
421 * You can have as many $(document).ready events on your page as you like.
422 * The functions are then executed in the order they were added.
424 * @example $(document).ready(function(){ Your code here... });
428 * @param Function fn The function to be executed when the DOM is ready.
432 // If the DOM is already ready
433 if ( jQuery.isReady )
434 // Execute the function immediately
437 // Otherwise, remember the function for later
439 // Add the function to the wait list
440 jQuery.readyList.push( f );
449 * All the code that makes DOM Ready work nicely.
454 // Handle when the DOM is ready
456 // Make sure that the DOM is not already loaded
457 if ( !jQuery.isReady ) {
458 // Remember that the DOM is ready
459 jQuery.isReady = true;
461 // If there are functions bound, to execute
462 if ( jQuery.readyList ) {
463 // Execute all of them
464 for ( var i = 0; i < jQuery.readyList.length; i++ )
465 jQuery.readyList[i].apply( document );
467 // Reset the list of functions
468 jQuery.readyList = null;
470 // Remove event lisenter to avoid memory leak
471 if ( jQuery.browser.mozilla || jQuery.browser.opera )
472 document.removeEventListener( "DOMContentLoaded", jQuery.ready, false );
480 * Bind a function to the scroll event of each matched element.
482 * @example $("p").scroll( function() { alert("Hello"); } );
483 * @before <p>Hello</p>
484 * @result <p onscroll="alert('Hello');">Hello</p>
488 * @param Function fn A function to bind to the scroll event on each of the matched elements.
493 * Bind a function to the submit event of each matched element.
495 * @example $("#myform").submit( function() {
496 * return $("input", this).val().length > 0;
498 * @before <form id="myform"><input /></form>
499 * @desc Prevents the form submission when the input has no value entered.
503 * @param Function fn A function to bind to the submit event on each of the matched elements.
508 * Trigger the submit event of each matched element. This causes all of the functions
509 * that have been bound to thet submit event to be executed.
511 * Note: This does not execute the submit method of the form element! If you need to
512 * submit the form via code, you have to use the DOM method, eg. $("form")[0].submit();
514 * @example $("form").submit();
515 * @desc Triggers all submit events registered for forms, but does not submit the form
523 * Bind a function to the focus event of each matched element.
525 * @example $("p").focus( function() { alert("Hello"); } );
526 * @before <p>Hello</p>
527 * @result <p onfocus="alert('Hello');">Hello</p>
531 * @param Function fn A function to bind to the focus event on each of the matched elements.
536 * Trigger the focus event of each matched element. This causes all of the functions
537 * that have been bound to thet focus event to be executed.
539 * Note: This does not execute the focus method of the underlying elements! If you need to
540 * focus an element via code, you have to use the DOM method, eg. $("#myinput")[0].focus();
542 * @example $("p").focus();
543 * @before <p onfocus="alert('Hello');">Hello</p>
544 * @result alert('Hello');
552 * Bind a function to the keydown event of each matched element.
554 * @example $("p").keydown( function() { alert("Hello"); } );
555 * @before <p>Hello</p>
556 * @result <p onkeydown="alert('Hello');">Hello</p>
560 * @param Function fn A function to bind to the keydown event on each of the matched elements.
565 * Bind a function to the dblclick event of each matched element.
567 * @example $("p").dblclick( function() { alert("Hello"); } );
568 * @before <p>Hello</p>
569 * @result <p ondblclick="alert('Hello');">Hello</p>
573 * @param Function fn A function to bind to the dblclick event on each of the matched elements.
578 * Bind a function to the keypress event of each matched element.
580 * @example $("p").keypress( function() { alert("Hello"); } );
581 * @before <p>Hello</p>
582 * @result <p onkeypress="alert('Hello');">Hello</p>
586 * @param Function fn A function to bind to the keypress event on each of the matched elements.
591 * Bind a function to the error event of each matched element.
593 * @example $("p").error( function() { alert("Hello"); } );
594 * @before <p>Hello</p>
595 * @result <p onerror="alert('Hello');">Hello</p>
599 * @param Function fn A function to bind to the error event on each of the matched elements.
604 * Bind a function to the blur event of each matched element.
606 * @example $("p").blur( function() { alert("Hello"); } );
607 * @before <p>Hello</p>
608 * @result <p onblur="alert('Hello');">Hello</p>
612 * @param Function fn A function to bind to the blur event on each of the matched elements.
617 * Trigger the blur event of each matched element. This causes all of the functions
618 * that have been bound to thet blur event to be executed.
620 * Note: This does not execute the blur method of the underlying elements! If you need to
621 * blur an element via code, you have to use the DOM method, eg. $("#myinput")[0].blur();
623 * @example $("p").blur();
624 * @before <p onblur="alert('Hello');">Hello</p>
625 * @result alert('Hello');
633 * Bind a function to the load event of each matched element.
635 * @example $("p").load( function() { alert("Hello"); } );
636 * @before <p>Hello</p>
637 * @result <p onload="alert('Hello');">Hello</p>
641 * @param Function fn A function to bind to the load event on each of the matched elements.
646 * Bind a function to the select event of each matched element.
648 * @example $("p").select( function() { alert("Hello"); } );
649 * @before <p>Hello</p>
650 * @result <p onselect="alert('Hello');">Hello</p>
654 * @param Function fn A function to bind to the select event on each of the matched elements.
659 * Trigger the select event of each matched element. This causes all of the functions
660 * that have been bound to thet select event to be executed.
662 * @example $("p").select();
663 * @before <p onselect="alert('Hello');">Hello</p>
664 * @result alert('Hello');
672 * Bind a function to the mouseup event of each matched element.
674 * @example $("p").mouseup( function() { alert("Hello"); } );
675 * @before <p>Hello</p>
676 * @result <p onmouseup="alert('Hello');">Hello</p>
680 * @param Function fn A function to bind to the mouseup event on each of the matched elements.
685 * Bind a function to the unload event of each matched element.
687 * @example $("p").unload( function() { alert("Hello"); } );
688 * @before <p>Hello</p>
689 * @result <p onunload="alert('Hello');">Hello</p>
693 * @param Function fn A function to bind to the unload event on each of the matched elements.
698 * Bind a function to the change event of each matched element.
700 * @example $("p").change( function() { alert("Hello"); } );
701 * @before <p>Hello</p>
702 * @result <p onchange="alert('Hello');">Hello</p>
706 * @param Function fn A function to bind to the change event on each of the matched elements.
711 * Bind a function to the mouseout event of each matched element.
713 * @example $("p").mouseout( function() { alert("Hello"); } );
714 * @before <p>Hello</p>
715 * @result <p onmouseout="alert('Hello');">Hello</p>
719 * @param Function fn A function to bind to the mouseout event on each of the matched elements.
724 * Bind a function to the keyup event of each matched element.
726 * @example $("p").keyup( function() { alert("Hello"); } );
727 * @before <p>Hello</p>
728 * @result <p onkeyup="alert('Hello');">Hello</p>
732 * @param Function fn A function to bind to the keyup event on each of the matched elements.
737 * Bind a function to the click event of each matched element.
739 * @example $("p").click( function() { alert("Hello"); } );
740 * @before <p>Hello</p>
741 * @result <p onclick="alert('Hello');">Hello</p>
745 * @param Function fn A function to bind to the click event on each of the matched elements.
750 * Trigger the click event of each matched element. This causes all of the functions
751 * that have been bound to thet click event to be executed.
753 * @example $("p").click();
754 * @before <p onclick="alert('Hello');">Hello</p>
755 * @result alert('Hello');
763 * Bind a function to the resize event of each matched element.
765 * @example $("p").resize( function() { alert("Hello"); } );
766 * @before <p>Hello</p>
767 * @result <p onresize="alert('Hello');">Hello</p>
771 * @param Function fn A function to bind to the resize event on each of the matched elements.
776 * Bind a function to the mousemove event of each matched element.
778 * @example $("p").mousemove( function() { alert("Hello"); } );
779 * @before <p>Hello</p>
780 * @result <p onmousemove="alert('Hello');">Hello</p>
784 * @param Function fn A function to bind to the mousemove event on each of the matched elements.
789 * Bind a function to the mousedown event of each matched element.
791 * @example $("p").mousedown( function() { alert("Hello"); } );
792 * @before <p>Hello</p>
793 * @result <p onmousedown="alert('Hello');">Hello</p>
797 * @param Function fn A function to bind to the mousedown event on each of the matched elements.
802 * Bind a function to the mouseover event of each matched element.
804 * @example $("p").mouseover( function() { alert("Hello"); } );
805 * @before <p>Hello</p>
806 * @result <p onmouseover="alert('Hello');">Hello</p>
810 * @param Function fn A function to bind to the mousedown event on each of the matched elements.
813 jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
814 "mousedown,mouseup,mousemove,mouseover,mouseout,change,select," +
815 "submit,keydown,keypress,keyup,error").split(","), function(i,o){
817 // Handle event binding
818 jQuery.fn[o] = function(f){
819 return f ? this.bind(o, f) : this.trigger(o);
824 // If Mozilla is used
825 if ( jQuery.browser.mozilla || jQuery.browser.opera )
826 // Use the handy event callback
827 document.addEventListener( "DOMContentLoaded", jQuery.ready, false );
829 // If IE is used, use the excellent hack by Matthias Miller
830 // http://www.outofhanwell.com/blog/index.php?title=the_window_onload_problem_revisited
831 else if ( jQuery.browser.msie ) {
833 // Only works if you document.write() it
834 document.write("<scr" + "ipt id=__ie_init defer=true " +
835 "src=//:><\/script>");
837 // Use the defer script hack
838 var script = document.getElementById("__ie_init");
840 // script does not exist if jQuery is loaded dynamically
842 script.onreadystatechange = function() {
843 if ( this.readyState != "complete" ) return;
844 this.parentNode.removeChild( this );
852 } else if ( jQuery.browser.safari )
853 // Continually check to see if the document.readyState is valid
854 jQuery.safariTimer = setInterval(function(){
855 // loaded and complete are both valid states
856 if ( document.readyState == "loaded" ||
857 document.readyState == "complete" ) {
859 // If either one are found, remove the timer
860 clearInterval( jQuery.safariTimer );
861 jQuery.safariTimer = null;
863 // and execute any waiting functions
868 // A fallback to window.onload, that will always work
869 jQuery.event.add( window, "load", jQuery.ready );
873 // Clean up after IE to avoid memory leaks
874 if (jQuery.browser.msie)
875 jQuery(window).one("unload", function() {
876 var global = jQuery.event.global;
877 for ( var type in global ) {
878 var els = global[type], i = els.length;
879 if ( i && type != 'unload' )
881 jQuery.event.remove(els[i-1], type);