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) {
58 var events = element.$events, ret;
61 // type is actually an event object here
62 if ( type && type.type ) {
63 handler = type.handler;
68 for ( type in events )
69 this.remove( element, type );
71 } else if ( events[type] ) {
72 // remove the given handler for the given type
74 delete events[type][handler.guid];
76 // remove all handlers for the given type
78 for ( handler in element.$events[type] )
79 delete events[type][handler];
81 // remove generic event handler if no more handlers exist
82 for ( ret in events[type] ) break;
84 ret = element["on" + type] = null;
89 // Remove the expando if it's no longer used
90 for ( ret in events ) break;
92 element.$events = null;
96 trigger: function(type, data, element) {
97 // Clone the incoming data, if any
98 data = jQuery.makeArray(data || []);
100 // Handle a global trigger
102 jQuery.each( this.global[type] || [], function(){
103 jQuery.event.trigger( type, data, this );
106 // Handle triggering a single element
108 var handler = element["on" + type ], val,
109 fn = jQuery.isFunction( element[ type ] );
112 // Pass along a fake event
113 data.unshift( this.fix({ type: type, target: element }) );
116 if ( (val = handler.apply( element, data )) !== false )
117 this.triggered = true;
120 if ( fn && val !== false )
123 this.triggered = false;
127 handle: function(event) {
128 // Handle the second event of a trigger and when
129 // an event is called after a page has unloaded
130 if ( typeof jQuery == "undefined" || jQuery.event.triggered ) return;
132 // Empty object is for triggered events with no data
133 event = jQuery.event.fix( event || window.event || {} );
135 // returned undefined or false
138 var c = this.$events[event.type];
140 var args = [].slice.call( arguments, 1 );
141 args.unshift( event );
144 // Pass in a reference to the handler function itself
145 // So that we can later remove it
146 args[0].handler = c[j];
147 args[0].data = c[j].data;
149 if ( c[j].apply( this, args ) === false ) {
150 event.preventDefault();
151 event.stopPropagation();
156 // Clean up added properties in IE to prevent memory leak
157 if (jQuery.browser.msie) event.target = event.preventDefault = event.stopPropagation = event.handler = event.data = null;
162 fix: function(event) {
163 // Fix target property, if necessary
164 if ( !event.target && event.srcElement )
165 event.target = event.srcElement;
167 // Calculate pageX/Y if missing and clientX/Y available
168 if ( event.pageX == undefined && event.clientX != undefined ) {
169 var e = document.documentElement, b = document.body;
170 event.pageX = event.clientX + (e.scrollLeft || b.scrollLeft);
171 event.pageY = event.clientY + (e.scrollTop || b.scrollTop);
174 // check if target is a textnode (safari)
175 if (jQuery.browser.safari && event.target.nodeType == 3) {
176 // store a copy of the original event object
177 // and clone because target is read only
178 var originalEvent = event;
179 event = jQuery.extend({}, originalEvent);
181 // get parentnode from textnode
182 event.target = originalEvent.target.parentNode;
184 // add preventDefault and stopPropagation since
185 // they will not work on the clone
186 event.preventDefault = function() {
187 return originalEvent.preventDefault();
189 event.stopPropagation = function() {
190 return originalEvent.stopPropagation();
194 // fix preventDefault and stopPropagation
195 if (!event.preventDefault)
196 event.preventDefault = function() {
197 this.returnValue = false;
200 if (!event.stopPropagation)
201 event.stopPropagation = function() {
202 this.cancelBubble = true;
212 * Binds a handler to a particular event (like click) for each matched element.
213 * The event handler is passed an event object that you can use to prevent
214 * default behaviour. To stop both default action and event bubbling, your handler
215 * has to return false.
217 * In most cases, you can define your event handlers as anonymous functions
218 * (see first example). In cases where that is not possible, you can pass additional
219 * data as the second parameter (and the handler function as the third), see
222 * @example $("p").bind("click", function(){
223 * alert( $(this).text() );
225 * @before <p>Hello</p>
226 * @result alert("Hello")
228 * @example function handler(event) {
229 * alert(event.data.foo);
231 * $("p").bind("click", {foo: "bar"}, handler)
232 * @result alert("bar")
233 * @desc Pass some additional data to the event handler.
235 * @example $("form").bind("submit", function() { return false; })
236 * @desc Cancel a default action and prevent it from bubbling by returning false
237 * from your function.
239 * @example $("form").bind("submit", function(event){
240 * event.preventDefault();
242 * @desc Cancel only the default action by using the preventDefault method.
245 * @example $("form").bind("submit", function(event){
246 * event.stopPropagation();
248 * @desc Stop only an event from bubbling by using the stopPropagation method.
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 bind: function( type, data, fn ) {
258 return this.each(function(){
259 jQuery.event.add( this, type, fn || data, data );
264 * Binds a handler to a particular event (like click) for each matched element.
265 * The handler is executed only once for each element. Otherwise, the same rules
266 * as described in bind() apply.
267 The event handler is passed an event object that you can use to prevent
268 * default behaviour. To stop both default action and event bubbling, your handler
269 * has to return false.
271 * In most cases, you can define your event handlers as anonymous functions
272 * (see first example). In cases where that is not possible, you can pass additional
273 * data as the second paramter (and the handler function as the third), see
276 * @example $("p").one("click", function(){
277 * alert( $(this).text() );
279 * @before <p>Hello</p>
280 * @result alert("Hello")
284 * @param String type An event type
285 * @param Object data (optional) Additional data passed to the event handler as event.data
286 * @param Function fn A function to bind to the event on each of the set of matched elements
289 one: function( type, data, fn ) {
290 return this.each(function(){
291 jQuery.event.add( this, type, function(event) {
292 jQuery(this).unbind(event);
293 return (fn || data).apply( this, arguments);
299 * The opposite of bind, removes a bound event from each of the matched
302 * Without any arguments, all bound events are removed.
304 * If the type is provided, all bound events of that type are removed.
306 * If the function that was passed to bind is provided as the second argument,
307 * only that specific event handler is removed.
309 * @example $("p").unbind()
310 * @before <p onclick="alert('Hello');">Hello</p>
311 * @result [ <p>Hello</p> ]
313 * @example $("p").unbind( "click" )
314 * @before <p onclick="alert('Hello');">Hello</p>
315 * @result [ <p>Hello</p> ]
317 * @example $("p").unbind( "click", function() { alert("Hello"); } )
318 * @before <p onclick="alert('Hello');">Hello</p>
319 * @result [ <p>Hello</p> ]
323 * @param String type (optional) An event type
324 * @param Function fn (optional) A function to unbind from the event on each of the set of matched elements
327 unbind: function( type, fn ) {
328 return this.each(function(){
329 jQuery.event.remove( this, type, fn );
334 * Trigger a type of event on every matched element. This will also cause
335 * the default action of the browser with the same name (if one exists)
336 * to be executed. For example, passing 'submit' to the trigger()
337 * function will also cause the browser to submit the form. This
338 * default action can be prevented by returning false from one of
339 * the functions bound to the event.
341 * You can also trigger custom events registered with bind.
343 * @example $("p").trigger("click")
344 * @before <p click="alert('hello')">Hello</p>
345 * @result alert('hello')
347 * @example $("p").click(function(event, a, b) {
348 * // when a normal click fires, a and b are undefined
349 * // for a trigger like below a refers too "foo" and b refers to "bar"
350 * }).trigger("click", ["foo", "bar"]);
351 * @desc Example of how to pass arbitrary data to an event
353 * @example $("p").bind("myEvent",function(event,message1,message2) {
354 * alert(message1 + ' ' + message2);
356 * $("p").trigger("myEvent",["Hello","World"]);
357 * @result alert('Hello World') // One for each paragraph
361 * @param String type An event type to trigger.
362 * @param Array data (optional) Additional data to pass as arguments (after the event object) to the event handler
365 trigger: function( type, data ) {
366 return this.each(function(){
367 jQuery.event.trigger( type, data, this );
372 * Toggle between two function calls every other click.
373 * Whenever a matched element is clicked, the first specified function
374 * is fired, when clicked again, the second is fired. All subsequent
375 * clicks continue to rotate through the two functions.
377 * Use unbind("click") to remove.
379 * @example $("p").toggle(function(){
380 * $(this).addClass("selected");
382 * $(this).removeClass("selected");
387 * @param Function even The function to execute on every even click.
388 * @param Function odd The function to execute on every odd click.
392 // Save reference to arguments for access in closure
395 return this.click(function(e) {
396 // Figure out which function to execute
397 this.lastToggle = this.lastToggle == 0 ? 1 : 0;
399 // Make sure that clicks stop
402 // and execute the function
403 return a[this.lastToggle].apply( this, [e] ) || false;
408 * A method for simulating hovering (moving the mouse on, and off,
409 * an object). This is a custom method which provides an 'in' to a
412 * Whenever the mouse cursor is moved over a matched
413 * element, the first specified function is fired. Whenever the mouse
414 * moves off of the element, the second specified function fires.
415 * Additionally, checks are in place to see if the mouse is still within
416 * the specified element itself (for example, an image inside of a div),
417 * and if it is, it will continue to 'hover', and not move out
418 * (a common error in using a mouseout event handler).
420 * @example $("p").hover(function(){
421 * $(this).addClass("hover");
423 * $(this).removeClass("hover");
428 * @param Function over The function to fire whenever the mouse is moved over a matched element.
429 * @param Function out The function to fire whenever the mouse is moved off of a matched element.
432 hover: function(f,g) {
434 // A private function for handling mouse 'hovering'
435 function handleHover(e) {
436 // Check if mouse(over|out) are still within the same parent element
437 var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
439 // Traverse up the tree
440 while ( p && p != this ) try { p = p.parentNode } catch(e) { p = this; };
442 // If we actually just moused on to a sub-element, ignore it
443 if ( p == this ) return false;
445 // Execute the right function
446 return (e.type == "mouseover" ? f : g).apply(this, [e]);
449 // Bind the function to the two event listeners
450 return this.mouseover(handleHover).mouseout(handleHover);
454 * Bind a function to be executed whenever the DOM is ready to be
455 * traversed and manipulated. This is probably the most important
456 * function included in the event module, as it can greatly improve
457 * the response times of your web applications.
459 * In a nutshell, this is a solid replacement for using window.onload,
460 * and attaching a function to that. By using this method, your bound function
461 * will be called the instant the DOM is ready to be read and manipulated,
462 * which is when what 99.99% of all JavaScript code needs to run.
464 * There is one argument passed to the ready event handler: A reference to
465 * the jQuery function. You can name that argument whatever you like, and
466 * can therefore stick with the $ alias without risk of naming collisions.
468 * Please ensure you have no code in your <body> onload event handler,
469 * otherwise $(document).ready() may not fire.
471 * You can have as many $(document).ready events on your page as you like.
472 * The functions are then executed in the order they were added.
474 * @example $(document).ready(function(){ Your code here... });
476 * @example jQuery(function($) {
477 * // Your code using failsafe $ alias here...
479 * @desc Uses both the [[Core#.24.28_fn_.29|shortcut]] for $(document).ready() and the argument
480 * to write failsafe jQuery code using the $ alias, without relying on the
485 * @param Function fn The function to be executed when the DOM is ready.
487 * @see $.noConflict()
491 // If the DOM is already ready
492 if ( jQuery.isReady )
493 // Execute the function immediately
494 f.apply( document, [jQuery] );
496 // Otherwise, remember the function for later
498 // Add the function to the wait list
499 jQuery.readyList.push( function() { return f.apply(this, [jQuery]) } );
508 * All the code that makes DOM Ready work nicely.
513 // Handle when the DOM is ready
515 // Make sure that the DOM is not already loaded
516 if ( !jQuery.isReady ) {
517 // Remember that the DOM is ready
518 jQuery.isReady = true;
520 // If there are functions bound, to execute
521 if ( jQuery.readyList ) {
522 // Execute all of them
523 jQuery.each( jQuery.readyList, function(){
524 this.apply( document );
527 // Reset the list of functions
528 jQuery.readyList = null;
530 // Remove event lisenter to avoid memory leak
531 if ( jQuery.browser.mozilla || jQuery.browser.opera )
532 document.removeEventListener( "DOMContentLoaded", jQuery.ready, false );
540 * Bind a function to the scroll event of each matched element.
542 * @example $("p").scroll( function() { alert("Hello"); } );
543 * @before <p>Hello</p>
544 * @result <p onscroll="alert('Hello');">Hello</p>
548 * @param Function fn A function to bind to the scroll event on each of the matched elements.
553 * Bind a function to the submit event of each matched element.
555 * @example $("#myform").submit( function() {
556 * return $("input", this).val().length > 0;
558 * @before <form id="myform"><input /></form>
559 * @desc Prevents the form submission when the input has no value entered.
563 * @param Function fn A function to bind to the submit event on each of the matched elements.
568 * Trigger the submit event of each matched element. This causes all of the functions
569 * that have been bound to that submit event to be executed, and calls the browser's
570 * default submit action on the matching element(s). This default action can be prevented
571 * by returning false from one of the functions bound to the submit event.
573 * Note: This does not execute the submit method of the form element! If you need to
574 * submit the form via code, you have to use the DOM method, eg. $("form")[0].submit();
576 * @example $("form").submit();
577 * @desc Triggers all submit events registered to the matched form(s), and submits them.
585 * Bind a function to the focus event of each matched element.
587 * @example $("p").focus( function() { alert("Hello"); } );
588 * @before <p>Hello</p>
589 * @result <p onfocus="alert('Hello');">Hello</p>
593 * @param Function fn A function to bind to the focus event on each of the matched elements.
598 * Trigger the focus event of each matched element. This causes all of the functions
599 * that have been bound to thet focus event to be executed.
601 * Note: This does not execute the focus method of the underlying elements! If you need to
602 * focus an element via code, you have to use the DOM method, eg. $("#myinput")[0].focus();
604 * @example $("p").focus();
605 * @before <p onfocus="alert('Hello');">Hello</p>
606 * @result alert('Hello');
614 * Bind a function to the keydown event of each matched element.
616 * @example $("p").keydown( function() { alert("Hello"); } );
617 * @before <p>Hello</p>
618 * @result <p onkeydown="alert('Hello');">Hello</p>
622 * @param Function fn A function to bind to the keydown event on each of the matched elements.
627 * Bind a function to the dblclick event of each matched element.
629 * @example $("p").dblclick( function() { alert("Hello"); } );
630 * @before <p>Hello</p>
631 * @result <p ondblclick="alert('Hello');">Hello</p>
635 * @param Function fn A function to bind to the dblclick event on each of the matched elements.
640 * Bind a function to the keypress event of each matched element.
642 * @example $("p").keypress( function() { alert("Hello"); } );
643 * @before <p>Hello</p>
644 * @result <p onkeypress="alert('Hello');">Hello</p>
648 * @param Function fn A function to bind to the keypress event on each of the matched elements.
653 * Bind a function to the error event of each matched element.
655 * @example $("p").error( function() { alert("Hello"); } );
656 * @before <p>Hello</p>
657 * @result <p onerror="alert('Hello');">Hello</p>
661 * @param Function fn A function to bind to the error event on each of the matched elements.
666 * Bind a function to the blur event of each matched element.
668 * @example $("p").blur( function() { alert("Hello"); } );
669 * @before <p>Hello</p>
670 * @result <p onblur="alert('Hello');">Hello</p>
674 * @param Function fn A function to bind to the blur event on each of the matched elements.
679 * Trigger the blur event of each matched element. This causes all of the functions
680 * that have been bound to that blur event to be executed, and calls the browser's
681 * default blur action on the matching element(s). This default action can be prevented
682 * by returning false from one of the functions bound to the blur event.
684 * Note: This does not execute the blur method of the underlying elements! If you need to
685 * blur an element via code, you have to use the DOM method, eg. $("#myinput")[0].blur();
687 * @example $("p").blur();
688 * @before <p onblur="alert('Hello');">Hello</p>
689 * @result alert('Hello');
697 * Bind a function to the load event of each matched element.
699 * @example $("p").load( function() { alert("Hello"); } );
700 * @before <p>Hello</p>
701 * @result <p onload="alert('Hello');">Hello</p>
705 * @param Function fn A function to bind to the load event on each of the matched elements.
710 * Bind a function to the select event of each matched element.
712 * @example $("p").select( function() { alert("Hello"); } );
713 * @before <p>Hello</p>
714 * @result <p onselect="alert('Hello');">Hello</p>
718 * @param Function fn A function to bind to the select event on each of the matched elements.
723 * Trigger the select event of each matched element. This causes all of the functions
724 * that have been bound to that select event to be executed, and calls the browser's
725 * default select action on the matching element(s). This default action can be prevented
726 * by returning false from one of the functions bound to the select event.
728 * @example $("p").select();
729 * @before <p onselect="alert('Hello');">Hello</p>
730 * @result alert('Hello');
738 * Bind a function to the mouseup event of each matched element.
740 * @example $("p").mouseup( function() { alert("Hello"); } );
741 * @before <p>Hello</p>
742 * @result <p onmouseup="alert('Hello');">Hello</p>
746 * @param Function fn A function to bind to the mouseup event on each of the matched elements.
751 * Bind a function to the unload event of each matched element.
753 * @example $("p").unload( function() { alert("Hello"); } );
754 * @before <p>Hello</p>
755 * @result <p onunload="alert('Hello');">Hello</p>
759 * @param Function fn A function to bind to the unload event on each of the matched elements.
764 * Bind a function to the change event of each matched element.
766 * @example $("p").change( function() { alert("Hello"); } );
767 * @before <p>Hello</p>
768 * @result <p onchange="alert('Hello');">Hello</p>
772 * @param Function fn A function to bind to the change event on each of the matched elements.
777 * Bind a function to the mouseout event of each matched element.
779 * @example $("p").mouseout( function() { alert("Hello"); } );
780 * @before <p>Hello</p>
781 * @result <p onmouseout="alert('Hello');">Hello</p>
785 * @param Function fn A function to bind to the mouseout event on each of the matched elements.
790 * Bind a function to the keyup event of each matched element.
792 * @example $("p").keyup( function() { alert("Hello"); } );
793 * @before <p>Hello</p>
794 * @result <p onkeyup="alert('Hello');">Hello</p>
798 * @param Function fn A function to bind to the keyup event on each of the matched elements.
803 * Bind a function to the click event of each matched element.
805 * @example $("p").click( function() { alert("Hello"); } );
806 * @before <p>Hello</p>
807 * @result <p onclick="alert('Hello');">Hello</p>
811 * @param Function fn A function to bind to the click event on each of the matched elements.
816 * Trigger the click event of each matched element. This causes all of the functions
817 * that have been bound to thet click event to be executed.
819 * @example $("p").click();
820 * @before <p onclick="alert('Hello');">Hello</p>
821 * @result alert('Hello');
829 * Bind a function to the resize event of each matched element.
831 * @example $("p").resize( function() { alert("Hello"); } );
832 * @before <p>Hello</p>
833 * @result <p onresize="alert('Hello');">Hello</p>
837 * @param Function fn A function to bind to the resize event on each of the matched elements.
842 * Bind a function to the mousemove event of each matched element.
844 * @example $("p").mousemove( function() { alert("Hello"); } );
845 * @before <p>Hello</p>
846 * @result <p onmousemove="alert('Hello');">Hello</p>
850 * @param Function fn A function to bind to the mousemove event on each of the matched elements.
855 * Bind a function to the mousedown event of each matched element.
857 * @example $("p").mousedown( function() { alert("Hello"); } );
858 * @before <p>Hello</p>
859 * @result <p onmousedown="alert('Hello');">Hello</p>
863 * @param Function fn A function to bind to the mousedown event on each of the matched elements.
868 * Bind a function to the mouseover event of each matched element.
870 * @example $("p").mouseover( function() { alert("Hello"); } );
871 * @before <p>Hello</p>
872 * @result <p onmouseover="alert('Hello');">Hello</p>
876 * @param Function fn A function to bind to the mousedown event on each of the matched elements.
879 jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
880 "mousedown,mouseup,mousemove,mouseover,mouseout,change,select," +
881 "submit,keydown,keypress,keyup,error").split(","), function(i,o){
883 // Handle event binding
884 jQuery.fn[o] = function(f){
885 return f ? this.bind(o, f) : this.trigger(o);
890 // If Mozilla is used
891 if ( jQuery.browser.mozilla || jQuery.browser.opera )
892 // Use the handy event callback
893 document.addEventListener( "DOMContentLoaded", jQuery.ready, false );
895 // If IE is used, use the excellent hack by Matthias Miller
896 // http://www.outofhanwell.com/blog/index.php?title=the_window_onload_problem_revisited
897 else if ( jQuery.browser.msie ) {
899 // Only works if you document.write() it
900 document.write("<scr" + "ipt id=__ie_init defer=true " +
901 "src=//:><\/script>");
903 // Use the defer script hack
904 var script = document.getElementById("__ie_init");
906 // script does not exist if jQuery is loaded dynamically
908 script.onreadystatechange = function() {
909 if ( this.readyState != "complete" ) return;
910 this.parentNode.removeChild( this );
918 } else if ( jQuery.browser.safari )
919 // Continually check to see if the document.readyState is valid
920 jQuery.safariTimer = setInterval(function(){
921 // loaded and complete are both valid states
922 if ( document.readyState == "loaded" ||
923 document.readyState == "complete" ) {
925 // If either one are found, remove the timer
926 clearInterval( jQuery.safariTimer );
927 jQuery.safariTimer = null;
929 // and execute any waiting functions
934 // A fallback to window.onload, that will always work
935 jQuery.event.add( window, "load", jQuery.ready );
939 // Clean up after IE to avoid memory leaks
940 if (jQuery.browser.msie)
941 jQuery(window).one("unload", function() {
942 var global = jQuery.event.global;
943 for ( var type in global ) {
944 var els = global[type], i = els.length;
945 if ( i && type != 'unload' )
947 jQuery.event.remove(els[i-1], type);