2 * A number of helper functions used for managing events.
3 * Many of the ideas behind this code orignated from
4 * Dean Edwards' addEvent library.
8 // Bind an event to an element
9 // Original by Dean Edwards
10 add: function(element, type, handler, data) {
11 // For whatever reason, IE has trouble passing the window object
12 // around, causing it to be cloned in the process
13 if ( jQuery.browser.msie && element.setInterval != undefined )
16 // if data is passed, bind to handler
17 if( data != undefined ) {
18 // Create temporary function pointer to original handler
21 // Create unique handler function, wrapped around original handler
22 handler = function() {
23 // Pass arguments and context to original handler
24 return fn.apply(this, arguments);
27 // Store data in unique handler
30 // Set the guid of unique handler to the same of original handler, so it can be removed
31 handler.guid = fn.guid;
34 // Make sure that the function being executed has a unique ID
36 handler.guid = this.guid++;
38 // Init the element's event structure
43 element.$handle = function() {
44 jQuery.event.handle.apply(element, arguments);
47 // Get the current list of functions bound to this event
48 var handlers = element.$events[type];
50 // Init the event handler queue
52 handlers = element.$events[type] = {};
54 // And bind the global event handler to the element
55 if (element.addEventListener)
56 element.addEventListener(type, element.$handle, false);
57 else if (element.attachEvent)
58 element.attachEvent("on" + type, element.$handle, false);
61 // Add the function to the element's handler list
62 handlers[handler.guid] = handler;
64 // Remember the function in a global list (for triggering)
65 if (!this.global[type])
66 this.global[type] = [];
67 this.global[type].push( element );
73 // Detach an event or set of events from an element
74 remove: function(element, type, handler) {
75 var events = element.$events, ret;
78 // type is actually an event object here
79 if ( type && type.type ) {
80 handler = type.handler;
85 for ( type in events )
86 this.remove( element, type );
88 } else if ( events[type] ) {
89 // remove the given handler for the given type
91 delete events[type][handler.guid];
93 // remove all handlers for the given type
95 for ( handler in element.$events[type] )
96 delete events[type][handler];
98 // remove generic event handler if no more handlers exist
99 for ( ret in events[type] ) break;
101 if (element.removeEventListener)
102 element.removeEventListener(type, element.$handle, false);
103 else if (element.detachEvent)
104 element.detachEvent("on" + type, element.$handle, false);
110 // Remove the expando if it's no longer used
111 for ( ret in events ) break;
113 element.$handle = element.$events = null;
117 trigger: function(type, data, element) {
118 // Clone the incoming data, if any
119 data = jQuery.makeArray(data || []);
121 // Handle a global trigger
123 jQuery.each( this.global[type] || [], function(){
124 jQuery.event.trigger( type, data, this );
127 // Handle triggering a single element
129 var val, ret, fn = jQuery.isFunction( element[ type ] );
131 // Pass along a fake event
132 data.unshift( this.fix({ type: type, target: element }) );
135 if ( (val = this.handle.apply( element, data )) !== false )
136 this.triggered = true;
138 if ( fn && val !== false && !jQuery.nodeName(element, 'a') )
141 this.triggered = false;
145 handle: function(event) {
146 // Handle the second event of a trigger and when
147 // an event is called after a page has unloaded
148 if ( typeof jQuery == "undefined" || jQuery.event.triggered ) return;
150 // Empty object is for triggered events with no data
151 event = jQuery.event.fix( event || window.event || {} );
153 // returned undefined or false
156 var c = this.$events[event.type];
158 var args = [].slice.call( arguments, 1 );
159 args.unshift( event );
162 // Pass in a reference to the handler function itself
163 // So that we can later remove it
164 args[0].handler = c[j];
165 args[0].data = c[j].data;
167 if ( c[j].apply( this, args ) === false ) {
168 event.preventDefault();
169 event.stopPropagation();
174 // Clean up added properties in IE to prevent memory leak
175 if (jQuery.browser.msie) event.target = event.preventDefault = event.stopPropagation = event.handler = event.data = null;
180 fix: function(event) {
181 // Fix target property, if necessary
182 if ( !event.target && event.srcElement )
183 event.target = event.srcElement;
185 // Calculate pageX/Y if missing and clientX/Y available
186 if ( event.pageX == undefined && event.clientX != undefined ) {
187 var e = document.documentElement, b = document.body;
188 event.pageX = event.clientX + (e.scrollLeft || b.scrollLeft);
189 event.pageY = event.clientY + (e.scrollTop || b.scrollTop);
192 // check if target is a textnode (safari)
193 if (jQuery.browser.safari && event.target.nodeType == 3) {
194 // store a copy of the original event object
195 // and clone because target is read only
196 var originalEvent = event;
197 event = jQuery.extend({}, originalEvent);
199 // get parentnode from textnode
200 event.target = originalEvent.target.parentNode;
202 // add preventDefault and stopPropagation since
203 // they will not work on the clone
204 event.preventDefault = function() {
205 return originalEvent.preventDefault();
207 event.stopPropagation = function() {
208 return originalEvent.stopPropagation();
212 // fix preventDefault and stopPropagation
213 if (!event.preventDefault)
214 event.preventDefault = function() {
215 this.returnValue = false;
218 if (!event.stopPropagation)
219 event.stopPropagation = function() {
220 this.cancelBubble = true;
230 * Binds a handler to a particular event (like click) for each matched element.
231 * The event handler is passed an event object that you can use to prevent
232 * default behaviour. To stop both default action and event bubbling, your handler
233 * has to return false.
235 * In most cases, you can define your event handlers as anonymous functions
236 * (see first example). In cases where that is not possible, you can pass additional
237 * data as the second parameter (and the handler function as the third), see
240 * @example $("p").bind("click", function(){
241 * alert( $(this).text() );
243 * @before <p>Hello</p>
244 * @result alert("Hello")
246 * @example function handler(event) {
247 * alert(event.data.foo);
249 * $("p").bind("click", {foo: "bar"}, handler)
250 * @result alert("bar")
251 * @desc Pass some additional data to the event handler.
253 * @example $("form").bind("submit", function() { return false; })
254 * @desc Cancel a default action and prevent it from bubbling by returning false
255 * from your function.
257 * @example $("form").bind("submit", function(event){
258 * event.preventDefault();
260 * @desc Cancel only the default action by using the preventDefault method.
263 * @example $("form").bind("submit", function(event){
264 * event.stopPropagation();
266 * @desc Stop only an event from bubbling by using the stopPropagation method.
270 * @param String type An event type
271 * @param Object data (optional) Additional data passed to the event handler as event.data
272 * @param Function fn A function to bind to the event on each of the set of matched elements
275 bind: function( type, data, fn ) {
276 return this.each(function(){
277 jQuery.event.add( this, type, fn || data, data );
282 * Binds a handler to a particular event (like click) for each matched element.
283 * The handler is executed only once for each element. Otherwise, the same rules
284 * as described in bind() apply.
285 The event handler is passed an event object that you can use to prevent
286 * default behaviour. To stop both default action and event bubbling, your handler
287 * has to return false.
289 * In most cases, you can define your event handlers as anonymous functions
290 * (see first example). In cases where that is not possible, you can pass additional
291 * data as the second paramter (and the handler function as the third), see
294 * @example $("p").one("click", function(){
295 * alert( $(this).text() );
297 * @before <p>Hello</p>
298 * @result alert("Hello")
302 * @param String type An event type
303 * @param Object data (optional) Additional data passed to the event handler as event.data
304 * @param Function fn A function to bind to the event on each of the set of matched elements
307 one: function( type, data, fn ) {
308 return this.each(function(){
309 jQuery.event.add( this, type, function(event) {
310 jQuery(this).unbind(event);
311 return (fn || data).apply( this, arguments);
317 * The opposite of bind, removes a bound event from each of the matched
320 * Without any arguments, all bound events are removed.
322 * If the type is provided, all bound events of that type are removed.
324 * If the function that was passed to bind is provided as the second argument,
325 * only that specific event handler is removed.
327 * @example $("p").unbind()
328 * @before <p onclick="alert('Hello');">Hello</p>
329 * @result [ <p>Hello</p> ]
331 * @example $("p").unbind( "click" )
332 * @before <p onclick="alert('Hello');">Hello</p>
333 * @result [ <p>Hello</p> ]
335 * @example $("p").unbind( "click", function() { alert("Hello"); } )
336 * @before <p onclick="alert('Hello');">Hello</p>
337 * @result [ <p>Hello</p> ]
341 * @param String type (optional) An event type
342 * @param Function fn (optional) A function to unbind from the event on each of the set of matched elements
345 unbind: function( type, fn ) {
346 return this.each(function(){
347 jQuery.event.remove( this, type, fn );
352 * Trigger a type of event on every matched element. This will also cause
353 * the default action of the browser with the same name (if one exists)
354 * to be executed. For example, passing 'submit' to the trigger()
355 * function will also cause the browser to submit the form. This
356 * default action can be prevented by returning false from one of
357 * the functions bound to the event.
359 * You can also trigger custom events registered with bind.
361 * @example $("p").trigger("click")
362 * @before <p click="alert('hello')">Hello</p>
363 * @result alert('hello')
365 * @example $("p").click(function(event, a, b) {
366 * // when a normal click fires, a and b are undefined
367 * // for a trigger like below a refers too "foo" and b refers to "bar"
368 * }).trigger("click", ["foo", "bar"]);
369 * @desc Example of how to pass arbitrary data to an event
371 * @example $("p").bind("myEvent",function(event,message1,message2) {
372 * alert(message1 + ' ' + message2);
374 * $("p").trigger("myEvent",["Hello","World"]);
375 * @result alert('Hello World') // One for each paragraph
379 * @param String type An event type to trigger.
380 * @param Array data (optional) Additional data to pass as arguments (after the event object) to the event handler
383 trigger: function( type, data ) {
384 return this.each(function(){
385 jQuery.event.trigger( type, data, this );
390 * Toggle between two function calls every other click.
391 * Whenever a matched element is clicked, the first specified function
392 * is fired, when clicked again, the second is fired. All subsequent
393 * clicks continue to rotate through the two functions.
395 * Use unbind("click") to remove.
397 * @example $("p").toggle(function(){
398 * $(this).addClass("selected");
400 * $(this).removeClass("selected");
405 * @param Function even The function to execute on every even click.
406 * @param Function odd The function to execute on every odd click.
410 // Save reference to arguments for access in closure
413 return this.click(function(e) {
414 // Figure out which function to execute
415 this.lastToggle = this.lastToggle == 0 ? 1 : 0;
417 // Make sure that clicks stop
420 // and execute the function
421 return a[this.lastToggle].apply( this, [e] ) || false;
426 * A method for simulating hovering (moving the mouse on, and off,
427 * an object). This is a custom method which provides an 'in' to a
430 * Whenever the mouse cursor is moved over a matched
431 * element, the first specified function is fired. Whenever the mouse
432 * moves off of the element, the second specified function fires.
433 * Additionally, checks are in place to see if the mouse is still within
434 * the specified element itself (for example, an image inside of a div),
435 * and if it is, it will continue to 'hover', and not move out
436 * (a common error in using a mouseout event handler).
438 * @example $("p").hover(function(){
439 * $(this).addClass("hover");
441 * $(this).removeClass("hover");
446 * @param Function over The function to fire whenever the mouse is moved over a matched element.
447 * @param Function out The function to fire whenever the mouse is moved off of a matched element.
450 hover: function(f,g) {
452 // A private function for handling mouse 'hovering'
453 function handleHover(e) {
454 // Check if mouse(over|out) are still within the same parent element
455 var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
457 // Traverse up the tree
458 while ( p && p != this ) try { p = p.parentNode } catch(e) { p = this; };
460 // If we actually just moused on to a sub-element, ignore it
461 if ( p == this ) return false;
463 // Execute the right function
464 return (e.type == "mouseover" ? f : g).apply(this, [e]);
467 // Bind the function to the two event listeners
468 return this.mouseover(handleHover).mouseout(handleHover);
472 * Bind a function to be executed whenever the DOM is ready to be
473 * traversed and manipulated. This is probably the most important
474 * function included in the event module, as it can greatly improve
475 * the response times of your web applications.
477 * In a nutshell, this is a solid replacement for using window.onload,
478 * and attaching a function to that. By using this method, your bound function
479 * will be called the instant the DOM is ready to be read and manipulated,
480 * which is when what 99.99% of all JavaScript code needs to run.
482 * There is one argument passed to the ready event handler: A reference to
483 * the jQuery function. You can name that argument whatever you like, and
484 * can therefore stick with the $ alias without risk of naming collisions.
486 * Please ensure you have no code in your <body> onload event handler,
487 * otherwise $(document).ready() may not fire.
489 * You can have as many $(document).ready events on your page as you like.
490 * The functions are then executed in the order they were added.
492 * @example $(document).ready(function(){ Your code here... });
494 * @example jQuery(function($) {
495 * // Your code using failsafe $ alias here...
497 * @desc Uses both the [[Core#.24.28_fn_.29|shortcut]] for $(document).ready() and the argument
498 * to write failsafe jQuery code using the $ alias, without relying on the
503 * @param Function fn The function to be executed when the DOM is ready.
505 * @see $.noConflict()
509 // If the DOM is already ready
510 if ( jQuery.isReady )
511 // Execute the function immediately
512 f.apply( document, [jQuery] );
514 // Otherwise, remember the function for later
516 // Add the function to the wait list
517 jQuery.readyList.push( function() { return f.apply(this, [jQuery]) } );
526 * All the code that makes DOM Ready work nicely.
531 // Handle when the DOM is ready
533 // Make sure that the DOM is not already loaded
534 if ( !jQuery.isReady ) {
535 // Remember that the DOM is ready
536 jQuery.isReady = true;
538 // If there are functions bound, to execute
539 if ( jQuery.readyList ) {
540 // Execute all of them
541 jQuery.each( jQuery.readyList, function(){
542 this.apply( document );
545 // Reset the list of functions
546 jQuery.readyList = null;
548 // Remove event lisenter to avoid memory leak
549 if ( jQuery.browser.mozilla || jQuery.browser.opera )
550 document.removeEventListener( "DOMContentLoaded", jQuery.ready, false );
558 * Bind a function to the scroll event of each matched element.
560 * @example $("p").scroll( function() { alert("Hello"); } );
561 * @before <p>Hello</p>
562 * @result <p onscroll="alert('Hello');">Hello</p>
566 * @param Function fn A function to bind to the scroll event on each of the matched elements.
571 * Bind a function to the submit event of each matched element.
573 * @example $("#myform").submit( function() {
574 * return $("input", this).val().length > 0;
576 * @before <form id="myform"><input /></form>
577 * @desc Prevents the form submission when the input has no value entered.
581 * @param Function fn A function to bind to the submit event on each of the matched elements.
586 * Trigger the submit event of each matched element. This causes all of the functions
587 * that have been bound to that submit event to be executed, and calls the browser's
588 * default submit action on the matching element(s). This default action can be prevented
589 * by returning false from one of the functions bound to the submit event.
591 * Note: This does not execute the submit method of the form element! If you need to
592 * submit the form via code, you have to use the DOM method, eg. $("form")[0].submit();
594 * @example $("form").submit();
595 * @desc Triggers all submit events registered to the matched form(s), and submits them.
603 * Bind a function to the focus event of each matched element.
605 * @example $("p").focus( function() { alert("Hello"); } );
606 * @before <p>Hello</p>
607 * @result <p onfocus="alert('Hello');">Hello</p>
611 * @param Function fn A function to bind to the focus event on each of the matched elements.
616 * Trigger the focus event of each matched element. This causes all of the functions
617 * that have been bound to thet focus event to be executed.
619 * Note: This does not execute the focus method of the underlying elements! If you need to
620 * focus an element via code, you have to use the DOM method, eg. $("#myinput")[0].focus();
622 * @example $("p").focus();
623 * @before <p onfocus="alert('Hello');">Hello</p>
624 * @result alert('Hello');
632 * Bind a function to the keydown event of each matched element.
634 * @example $("p").keydown( function() { alert("Hello"); } );
635 * @before <p>Hello</p>
636 * @result <p onkeydown="alert('Hello');">Hello</p>
640 * @param Function fn A function to bind to the keydown event on each of the matched elements.
645 * Bind a function to the dblclick event of each matched element.
647 * @example $("p").dblclick( function() { alert("Hello"); } );
648 * @before <p>Hello</p>
649 * @result <p ondblclick="alert('Hello');">Hello</p>
653 * @param Function fn A function to bind to the dblclick event on each of the matched elements.
658 * Bind a function to the keypress event of each matched element.
660 * @example $("p").keypress( function() { alert("Hello"); } );
661 * @before <p>Hello</p>
662 * @result <p onkeypress="alert('Hello');">Hello</p>
666 * @param Function fn A function to bind to the keypress event on each of the matched elements.
671 * Bind a function to the error event of each matched element.
673 * @example $("p").error( function() { alert("Hello"); } );
674 * @before <p>Hello</p>
675 * @result <p onerror="alert('Hello');">Hello</p>
679 * @param Function fn A function to bind to the error event on each of the matched elements.
684 * Bind a function to the blur event of each matched element.
686 * @example $("p").blur( function() { alert("Hello"); } );
687 * @before <p>Hello</p>
688 * @result <p onblur="alert('Hello');">Hello</p>
692 * @param Function fn A function to bind to the blur event on each of the matched elements.
697 * Trigger the blur event of each matched element. This causes all of the functions
698 * that have been bound to that blur event to be executed, and calls the browser's
699 * default blur action on the matching element(s). This default action can be prevented
700 * by returning false from one of the functions bound to the blur event.
702 * Note: This does not execute the blur method of the underlying elements! If you need to
703 * blur an element via code, you have to use the DOM method, eg. $("#myinput")[0].blur();
705 * @example $("p").blur();
706 * @before <p onblur="alert('Hello');">Hello</p>
707 * @result alert('Hello');
715 * Bind a function to the load event of each matched element.
717 * @example $("p").load( function() { alert("Hello"); } );
718 * @before <p>Hello</p>
719 * @result <p onload="alert('Hello');">Hello</p>
723 * @param Function fn A function to bind to the load event on each of the matched elements.
728 * Bind a function to the select event of each matched element.
730 * @example $("p").select( function() { alert("Hello"); } );
731 * @before <p>Hello</p>
732 * @result <p onselect="alert('Hello');">Hello</p>
736 * @param Function fn A function to bind to the select event on each of the matched elements.
741 * Trigger the select event of each matched element. This causes all of the functions
742 * that have been bound to that select event to be executed, and calls the browser's
743 * default select action on the matching element(s). This default action can be prevented
744 * by returning false from one of the functions bound to the select event.
746 * @example $("p").select();
747 * @before <p onselect="alert('Hello');">Hello</p>
748 * @result alert('Hello');
756 * Bind a function to the mouseup event of each matched element.
758 * @example $("p").mouseup( function() { alert("Hello"); } );
759 * @before <p>Hello</p>
760 * @result <p onmouseup="alert('Hello');">Hello</p>
764 * @param Function fn A function to bind to the mouseup event on each of the matched elements.
769 * Bind a function to the unload event of each matched element.
771 * @example $("p").unload( function() { alert("Hello"); } );
772 * @before <p>Hello</p>
773 * @result <p onunload="alert('Hello');">Hello</p>
777 * @param Function fn A function to bind to the unload event on each of the matched elements.
782 * Bind a function to the change event of each matched element.
784 * @example $("p").change( function() { alert("Hello"); } );
785 * @before <p>Hello</p>
786 * @result <p onchange="alert('Hello');">Hello</p>
790 * @param Function fn A function to bind to the change event on each of the matched elements.
795 * Bind a function to the mouseout event of each matched element.
797 * @example $("p").mouseout( function() { alert("Hello"); } );
798 * @before <p>Hello</p>
799 * @result <p onmouseout="alert('Hello');">Hello</p>
803 * @param Function fn A function to bind to the mouseout event on each of the matched elements.
808 * Bind a function to the keyup event of each matched element.
810 * @example $("p").keyup( function() { alert("Hello"); } );
811 * @before <p>Hello</p>
812 * @result <p onkeyup="alert('Hello');">Hello</p>
816 * @param Function fn A function to bind to the keyup event on each of the matched elements.
821 * Bind a function to the click event of each matched element.
823 * @example $("p").click( function() { alert("Hello"); } );
824 * @before <p>Hello</p>
825 * @result <p onclick="alert('Hello');">Hello</p>
829 * @param Function fn A function to bind to the click event on each of the matched elements.
834 * Trigger the click event of each matched element. This causes all of the functions
835 * that have been bound to thet click event to be executed.
837 * @example $("p").click();
838 * @before <p onclick="alert('Hello');">Hello</p>
839 * @result alert('Hello');
847 * Bind a function to the resize event of each matched element.
849 * @example $("p").resize( function() { alert("Hello"); } );
850 * @before <p>Hello</p>
851 * @result <p onresize="alert('Hello');">Hello</p>
855 * @param Function fn A function to bind to the resize event on each of the matched elements.
860 * Bind a function to the mousemove event of each matched element.
862 * @example $("p").mousemove( function() { alert("Hello"); } );
863 * @before <p>Hello</p>
864 * @result <p onmousemove="alert('Hello');">Hello</p>
868 * @param Function fn A function to bind to the mousemove event on each of the matched elements.
873 * Bind a function to the mousedown event of each matched element.
875 * @example $("p").mousedown( function() { alert("Hello"); } );
876 * @before <p>Hello</p>
877 * @result <p onmousedown="alert('Hello');">Hello</p>
881 * @param Function fn A function to bind to the mousedown event on each of the matched elements.
886 * Bind a function to the mouseover event of each matched element.
888 * @example $("p").mouseover( function() { alert("Hello"); } );
889 * @before <p>Hello</p>
890 * @result <p onmouseover="alert('Hello');">Hello</p>
894 * @param Function fn A function to bind to the mousedown event on each of the matched elements.
897 jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
898 "mousedown,mouseup,mousemove,mouseover,mouseout,change,select," +
899 "submit,keydown,keypress,keyup,error").split(","), function(i,o){
901 // Handle event binding
902 jQuery.fn[o] = function(f){
903 return f ? this.bind(o, f) : this.trigger(o);
908 // If Mozilla is used
909 if ( jQuery.browser.mozilla || jQuery.browser.opera )
910 // Use the handy event callback
911 document.addEventListener( "DOMContentLoaded", jQuery.ready, false );
913 // If IE is used, use the excellent hack by Matthias Miller
914 // http://www.outofhanwell.com/blog/index.php?title=the_window_onload_problem_revisited
915 else if ( jQuery.browser.msie ) {
917 // Only works if you document.write() it
918 document.write("<scr" + "ipt id=__ie_init defer=true " +
919 "src=//:><\/script>");
921 // Use the defer script hack
922 var script = document.getElementById("__ie_init");
924 // script does not exist if jQuery is loaded dynamically
926 script.onreadystatechange = function() {
927 if ( this.readyState != "complete" ) return;
928 this.parentNode.removeChild( this );
936 } else if ( jQuery.browser.safari )
937 // Continually check to see if the document.readyState is valid
938 jQuery.safariTimer = setInterval(function(){
939 // loaded and complete are both valid states
940 if ( document.readyState == "loaded" ||
941 document.readyState == "complete" ) {
943 // If either one are found, remove the timer
944 clearInterval( jQuery.safariTimer );
945 jQuery.safariTimer = null;
947 // and execute any waiting functions
952 // A fallback to window.onload, that will always work
953 jQuery.event.add( window, "load", jQuery.ready );
957 // Clean up after IE to avoid memory leaks
958 if (jQuery.browser.msie)
959 jQuery(window).one("unload", function() {
960 var global = jQuery.event.global;
961 for ( var type in global ) {
962 var els = global[type], i = els.length;
963 if ( i && type != 'unload' )
965 jQuery.event.remove(els[i-1], type);