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 if (element.$events) {
60 if ( type && type.type ) { // type is actually an event object here
61 handler = type.handler;
65 if (type && element.$events[type])
66 // remove the given handler for the given type
68 delete element.$events[type][handler.guid];
70 // remove all handlers for the given type
72 for ( i in element.$events[type] )
73 delete element.$events[type][i];
75 // remove all handlers
77 for ( j in element.$events )
78 this.remove( element, j );
80 // remove event handler if no more handlers exist
81 for ( k in element.$events[type] )
86 if (!k) element["on" + type] = null;
90 trigger: function(type, data, element) {
91 // Clone the incoming data, if any
92 data = jQuery.makeArray(data || []);
94 // Handle a global trigger
96 jQuery.each( this.global[type] || [], function(){
97 jQuery.event.trigger( type, data, this );
100 // Handle triggering a single element
102 var handler = element["on" + type ], val,
103 fn = jQuery.isFunction( element[ type ] );
106 // Pass along a fake event
107 data.unshift( this.fix({ type: type, target: element }) );
110 if ( (val = handler.apply( element, data )) !== false )
111 this.triggered = true;
114 if ( fn && val !== false )
117 this.triggered = false;
121 handle: function(event) {
122 // Handle the second event of a trigger and when
123 // an event is called after a page has unloaded
124 if ( typeof jQuery == "undefined" || jQuery.event.triggered ) return;
126 // Empty object is for triggered events with no data
127 event = jQuery.event.fix( event || window.event || {} );
129 // returned undefined or false
132 var c = this.$events[event.type];
134 var args = [].slice.call( arguments, 1 );
135 args.unshift( event );
138 // Pass in a reference to the handler function itself
139 // So that we can later remove it
140 args[0].handler = c[j];
141 args[0].data = c[j].data;
143 if ( c[j].apply( this, args ) === false ) {
144 event.preventDefault();
145 event.stopPropagation();
150 // Clean up added properties in IE to prevent memory leak
151 if (jQuery.browser.msie) event.target = event.preventDefault = event.stopPropagation = event.handler = event.data = null;
156 fix: function(event) {
157 // Fix target property, if necessary
158 if ( !event.target && event.srcElement )
159 event.target = event.srcElement;
161 // Calculate pageX/Y if missing and clientX/Y available
162 if ( event.pageX == undefined && event.clientX != undefined ) {
163 var e = document.documentElement, b = document.body;
164 event.pageX = event.clientX + (e.scrollLeft || b.scrollLeft);
165 event.pageY = event.clientY + (e.scrollTop || b.scrollTop);
168 // check if target is a textnode (safari)
169 if (jQuery.browser.safari && event.target.nodeType == 3) {
170 // store a copy of the original event object
171 // and clone because target is read only
172 var originalEvent = event;
173 event = jQuery.extend({}, originalEvent);
175 // get parentnode from textnode
176 event.target = originalEvent.target.parentNode;
178 // add preventDefault and stopPropagation since
179 // they will not work on the clone
180 event.preventDefault = function() {
181 return originalEvent.preventDefault();
183 event.stopPropagation = function() {
184 return originalEvent.stopPropagation();
188 // fix preventDefault and stopPropagation
189 if (!event.preventDefault)
190 event.preventDefault = function() {
191 this.returnValue = false;
194 if (!event.stopPropagation)
195 event.stopPropagation = function() {
196 this.cancelBubble = true;
206 * Binds a handler to a particular event (like click) for each matched element.
207 * The event handler is passed an event object that you can use to prevent
208 * default behaviour. To stop both default action and event bubbling, your handler
209 * has to return false.
211 * In most cases, you can define your event handlers as anonymous functions
212 * (see first example). In cases where that is not possible, you can pass additional
213 * data as the second parameter (and the handler function as the third), see
216 * @example $("p").bind("click", function(){
217 * alert( $(this).text() );
219 * @before <p>Hello</p>
220 * @result alert("Hello")
222 * @example function handler(event) {
223 * alert(event.data.foo);
225 * $("p").bind("click", {foo: "bar"}, handler)
226 * @result alert("bar")
227 * @desc Pass some additional data to the event handler.
229 * @example $("form").bind("submit", function() { return false; })
230 * @desc Cancel a default action and prevent it from bubbling by returning false
231 * from your function.
233 * @example $("form").bind("submit", function(event){
234 * event.preventDefault();
236 * @desc Cancel only the default action by using the preventDefault method.
239 * @example $("form").bind("submit", function(event){
240 * event.stopPropagation();
242 * @desc Stop only an event from bubbling by using the stopPropagation method.
246 * @param String type An event type
247 * @param Object data (optional) Additional data passed to the event handler as event.data
248 * @param Function fn A function to bind to the event on each of the set of matched elements
251 bind: function( type, data, fn ) {
252 return this.each(function(){
253 jQuery.event.add( this, type, fn || data, data );
258 * Binds a handler to a particular event (like click) for each matched element.
259 * The handler is executed only once for each element. Otherwise, the same rules
260 * as described in bind() apply.
261 The event handler is passed an event object that you can use to prevent
262 * default behaviour. To stop both default action and event bubbling, your handler
263 * has to return false.
265 * In most cases, you can define your event handlers as anonymous functions
266 * (see first example). In cases where that is not possible, you can pass additional
267 * data as the second paramter (and the handler function as the third), see
270 * @example $("p").one("click", function(){
271 * alert( $(this).text() );
273 * @before <p>Hello</p>
274 * @result alert("Hello")
278 * @param String type An event type
279 * @param Object data (optional) Additional data passed to the event handler as event.data
280 * @param Function fn A function to bind to the event on each of the set of matched elements
283 one: function( type, data, fn ) {
284 return this.each(function(){
285 jQuery.event.add( this, type, function(event) {
286 jQuery(this).unbind(event);
287 return (fn || data).apply( this, arguments);
293 * The opposite of bind, removes a bound event from each of the matched
296 * Without any arguments, all bound events are removed.
298 * If the type is provided, all bound events of that type are removed.
300 * If the function that was passed to bind is provided as the second argument,
301 * only that specific event handler is removed.
303 * @example $("p").unbind()
304 * @before <p onclick="alert('Hello');">Hello</p>
305 * @result [ <p>Hello</p> ]
307 * @example $("p").unbind( "click" )
308 * @before <p onclick="alert('Hello');">Hello</p>
309 * @result [ <p>Hello</p> ]
311 * @example $("p").unbind( "click", function() { alert("Hello"); } )
312 * @before <p onclick="alert('Hello');">Hello</p>
313 * @result [ <p>Hello</p> ]
317 * @param String type (optional) An event type
318 * @param Function fn (optional) A function to unbind from the event on each of the set of matched elements
321 unbind: function( type, fn ) {
322 return this.each(function(){
323 jQuery.event.remove( this, type, fn );
328 * Trigger a type of event on every matched element. This will also cause
329 * the default action of the browser with the same name (if one exists)
330 * to be executed. For example, passing 'submit' to the trigger()
331 * function will also cause the browser to submit the form. This
332 * default action can be prevented by returning false from one of
333 * the functions bound to the event.
335 * You can also trigger custom events registered with bind.
337 * @example $("p").trigger("click")
338 * @before <p click="alert('hello')">Hello</p>
339 * @result alert('hello')
341 * @example $("p").click(function(event, a, b) {
342 * // when a normal click fires, a and b are undefined
343 * // for a trigger like below a refers too "foo" and b refers to "bar"
344 * }).trigger("click", ["foo", "bar"]);
345 * @desc Example of how to pass arbitrary data to an event
347 * @example $("p").bind("myEvent",function(event,message1,message2) {
348 * alert(message1 + ' ' + message2);
350 * $("p").trigger("myEvent",["Hello","World"]);
351 * @result alert('Hello World') // One for each paragraph
355 * @param String type An event type to trigger.
356 * @param Array data (optional) Additional data to pass as arguments (after the event object) to the event handler
359 trigger: function( type, data ) {
360 return this.each(function(){
361 jQuery.event.trigger( type, data, this );
366 * Toggle between two function calls every other click.
367 * Whenever a matched element is clicked, the first specified function
368 * is fired, when clicked again, the second is fired. All subsequent
369 * clicks continue to rotate through the two functions.
371 * Use unbind("click") to remove.
373 * @example $("p").toggle(function(){
374 * $(this).addClass("selected");
376 * $(this).removeClass("selected");
381 * @param Function even The function to execute on every even click.
382 * @param Function odd The function to execute on every odd click.
386 // Save reference to arguments for access in closure
389 return this.click(function(e) {
390 // Figure out which function to execute
391 this.lastToggle = this.lastToggle == 0 ? 1 : 0;
393 // Make sure that clicks stop
396 // and execute the function
397 return a[this.lastToggle].apply( this, [e] ) || false;
402 * A method for simulating hovering (moving the mouse on, and off,
403 * an object). This is a custom method which provides an 'in' to a
406 * Whenever the mouse cursor is moved over a matched
407 * element, the first specified function is fired. Whenever the mouse
408 * moves off of the element, the second specified function fires.
409 * Additionally, checks are in place to see if the mouse is still within
410 * the specified element itself (for example, an image inside of a div),
411 * and if it is, it will continue to 'hover', and not move out
412 * (a common error in using a mouseout event handler).
414 * @example $("p").hover(function(){
415 * $(this).addClass("hover");
417 * $(this).removeClass("hover");
422 * @param Function over The function to fire whenever the mouse is moved over a matched element.
423 * @param Function out The function to fire whenever the mouse is moved off of a matched element.
426 hover: function(f,g) {
428 // A private function for handling mouse 'hovering'
429 function handleHover(e) {
430 // Check if mouse(over|out) are still within the same parent element
431 var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
433 // Traverse up the tree
434 while ( p && p != this ) try { p = p.parentNode } catch(e) { p = this; };
436 // If we actually just moused on to a sub-element, ignore it
437 if ( p == this ) return false;
439 // Execute the right function
440 return (e.type == "mouseover" ? f : g).apply(this, [e]);
443 // Bind the function to the two event listeners
444 return this.mouseover(handleHover).mouseout(handleHover);
448 * Bind a function to be executed whenever the DOM is ready to be
449 * traversed and manipulated. This is probably the most important
450 * function included in the event module, as it can greatly improve
451 * the response times of your web applications.
453 * In a nutshell, this is a solid replacement for using window.onload,
454 * and attaching a function to that. By using this method, your bound function
455 * will be called the instant the DOM is ready to be read and manipulated,
456 * which is when what 99.99% of all JavaScript code needs to run.
458 * There is one argument passed to the ready event handler: A reference to
459 * the jQuery function. You can name that argument whatever you like, and
460 * can therefore stick with the $ alias without risk of naming collisions.
462 * Please ensure you have no code in your <body> onload event handler,
463 * otherwise $(document).ready() may not fire.
465 * You can have as many $(document).ready events on your page as you like.
466 * The functions are then executed in the order they were added.
468 * @example $(document).ready(function(){ Your code here... });
470 * @example jQuery(function($) {
471 * // Your code using failsafe $ alias here...
473 * @desc Uses both the [[Core#.24.28_fn_.29|shortcut]] for $(document).ready() and the argument
474 * to write failsafe jQuery code using the $ alias, without relying on the
479 * @param Function fn The function to be executed when the DOM is ready.
481 * @see $.noConflict()
485 // If the DOM is already ready
486 if ( jQuery.isReady )
487 // Execute the function immediately
488 f.apply( document, [jQuery] );
490 // Otherwise, remember the function for later
492 // Add the function to the wait list
493 jQuery.readyList.push( function() { return f.apply(this, [jQuery]) } );
502 * All the code that makes DOM Ready work nicely.
507 // Handle when the DOM is ready
509 // Make sure that the DOM is not already loaded
510 if ( !jQuery.isReady ) {
511 // Remember that the DOM is ready
512 jQuery.isReady = true;
514 // If there are functions bound, to execute
515 if ( jQuery.readyList ) {
516 // Execute all of them
517 jQuery.each( jQuery.readyList, function(){
518 this.apply( document );
521 // Reset the list of functions
522 jQuery.readyList = null;
524 // Remove event lisenter to avoid memory leak
525 if ( jQuery.browser.mozilla || jQuery.browser.opera )
526 document.removeEventListener( "DOMContentLoaded", jQuery.ready, false );
534 * Bind a function to the scroll event of each matched element.
536 * @example $("p").scroll( function() { alert("Hello"); } );
537 * @before <p>Hello</p>
538 * @result <p onscroll="alert('Hello');">Hello</p>
542 * @param Function fn A function to bind to the scroll event on each of the matched elements.
547 * Bind a function to the submit event of each matched element.
549 * @example $("#myform").submit( function() {
550 * return $("input", this).val().length > 0;
552 * @before <form id="myform"><input /></form>
553 * @desc Prevents the form submission when the input has no value entered.
557 * @param Function fn A function to bind to the submit event on each of the matched elements.
562 * Trigger the submit event of each matched element. This causes all of the functions
563 * that have been bound to that submit event to be executed, and calls the browser's
564 * default submit action on the matching element(s). This default action can be prevented
565 * by returning false from one of the functions bound to the submit event.
567 * Note: This does not execute the submit method of the form element! If you need to
568 * submit the form via code, you have to use the DOM method, eg. $("form")[0].submit();
570 * @example $("form").submit();
571 * @desc Triggers all submit events registered to the matched form(s), and submits them.
579 * Bind a function to the focus event of each matched element.
581 * @example $("p").focus( function() { alert("Hello"); } );
582 * @before <p>Hello</p>
583 * @result <p onfocus="alert('Hello');">Hello</p>
587 * @param Function fn A function to bind to the focus event on each of the matched elements.
592 * Trigger the focus event of each matched element. This causes all of the functions
593 * that have been bound to thet focus event to be executed.
595 * Note: This does not execute the focus method of the underlying elements! If you need to
596 * focus an element via code, you have to use the DOM method, eg. $("#myinput")[0].focus();
598 * @example $("p").focus();
599 * @before <p onfocus="alert('Hello');">Hello</p>
600 * @result alert('Hello');
608 * Bind a function to the keydown event of each matched element.
610 * @example $("p").keydown( function() { alert("Hello"); } );
611 * @before <p>Hello</p>
612 * @result <p onkeydown="alert('Hello');">Hello</p>
616 * @param Function fn A function to bind to the keydown event on each of the matched elements.
621 * Bind a function to the dblclick event of each matched element.
623 * @example $("p").dblclick( function() { alert("Hello"); } );
624 * @before <p>Hello</p>
625 * @result <p ondblclick="alert('Hello');">Hello</p>
629 * @param Function fn A function to bind to the dblclick event on each of the matched elements.
634 * Bind a function to the keypress event of each matched element.
636 * @example $("p").keypress( function() { alert("Hello"); } );
637 * @before <p>Hello</p>
638 * @result <p onkeypress="alert('Hello');">Hello</p>
642 * @param Function fn A function to bind to the keypress event on each of the matched elements.
647 * Bind a function to the error event of each matched element.
649 * @example $("p").error( function() { alert("Hello"); } );
650 * @before <p>Hello</p>
651 * @result <p onerror="alert('Hello');">Hello</p>
655 * @param Function fn A function to bind to the error event on each of the matched elements.
660 * Bind a function to the blur event of each matched element.
662 * @example $("p").blur( function() { alert("Hello"); } );
663 * @before <p>Hello</p>
664 * @result <p onblur="alert('Hello');">Hello</p>
668 * @param Function fn A function to bind to the blur event on each of the matched elements.
673 * Trigger the blur event of each matched element. This causes all of the functions
674 * that have been bound to that blur event to be executed, and calls the browser's
675 * default blur action on the matching element(s). This default action can be prevented
676 * by returning false from one of the functions bound to the blur event.
678 * Note: This does not execute the blur method of the underlying elements! If you need to
679 * blur an element via code, you have to use the DOM method, eg. $("#myinput")[0].blur();
681 * @example $("p").blur();
682 * @before <p onblur="alert('Hello');">Hello</p>
683 * @result alert('Hello');
691 * Bind a function to the load event of each matched element.
693 * @example $("p").load( function() { alert("Hello"); } );
694 * @before <p>Hello</p>
695 * @result <p onload="alert('Hello');">Hello</p>
699 * @param Function fn A function to bind to the load event on each of the matched elements.
704 * Bind a function to the select event of each matched element.
706 * @example $("p").select( function() { alert("Hello"); } );
707 * @before <p>Hello</p>
708 * @result <p onselect="alert('Hello');">Hello</p>
712 * @param Function fn A function to bind to the select event on each of the matched elements.
717 * Trigger the select event of each matched element. This causes all of the functions
718 * that have been bound to that select event to be executed, and calls the browser's
719 * default select action on the matching element(s). This default action can be prevented
720 * by returning false from one of the functions bound to the select event.
722 * @example $("p").select();
723 * @before <p onselect="alert('Hello');">Hello</p>
724 * @result alert('Hello');
732 * Bind a function to the mouseup event of each matched element.
734 * @example $("p").mouseup( function() { alert("Hello"); } );
735 * @before <p>Hello</p>
736 * @result <p onmouseup="alert('Hello');">Hello</p>
740 * @param Function fn A function to bind to the mouseup event on each of the matched elements.
745 * Bind a function to the unload event of each matched element.
747 * @example $("p").unload( function() { alert("Hello"); } );
748 * @before <p>Hello</p>
749 * @result <p onunload="alert('Hello');">Hello</p>
753 * @param Function fn A function to bind to the unload event on each of the matched elements.
758 * Bind a function to the change event of each matched element.
760 * @example $("p").change( function() { alert("Hello"); } );
761 * @before <p>Hello</p>
762 * @result <p onchange="alert('Hello');">Hello</p>
766 * @param Function fn A function to bind to the change event on each of the matched elements.
771 * Bind a function to the mouseout event of each matched element.
773 * @example $("p").mouseout( function() { alert("Hello"); } );
774 * @before <p>Hello</p>
775 * @result <p onmouseout="alert('Hello');">Hello</p>
779 * @param Function fn A function to bind to the mouseout event on each of the matched elements.
784 * Bind a function to the keyup event of each matched element.
786 * @example $("p").keyup( function() { alert("Hello"); } );
787 * @before <p>Hello</p>
788 * @result <p onkeyup="alert('Hello');">Hello</p>
792 * @param Function fn A function to bind to the keyup event on each of the matched elements.
797 * Bind a function to the click event of each matched element.
799 * @example $("p").click( function() { alert("Hello"); } );
800 * @before <p>Hello</p>
801 * @result <p onclick="alert('Hello');">Hello</p>
805 * @param Function fn A function to bind to the click event on each of the matched elements.
810 * Trigger the click event of each matched element. This causes all of the functions
811 * that have been bound to thet click event to be executed.
813 * @example $("p").click();
814 * @before <p onclick="alert('Hello');">Hello</p>
815 * @result alert('Hello');
823 * Bind a function to the resize event of each matched element.
825 * @example $("p").resize( function() { alert("Hello"); } );
826 * @before <p>Hello</p>
827 * @result <p onresize="alert('Hello');">Hello</p>
831 * @param Function fn A function to bind to the resize event on each of the matched elements.
836 * Bind a function to the mousemove event of each matched element.
838 * @example $("p").mousemove( function() { alert("Hello"); } );
839 * @before <p>Hello</p>
840 * @result <p onmousemove="alert('Hello');">Hello</p>
844 * @param Function fn A function to bind to the mousemove event on each of the matched elements.
849 * Bind a function to the mousedown event of each matched element.
851 * @example $("p").mousedown( function() { alert("Hello"); } );
852 * @before <p>Hello</p>
853 * @result <p onmousedown="alert('Hello');">Hello</p>
857 * @param Function fn A function to bind to the mousedown event on each of the matched elements.
862 * Bind a function to the mouseover event of each matched element.
864 * @example $("p").mouseover( function() { alert("Hello"); } );
865 * @before <p>Hello</p>
866 * @result <p onmouseover="alert('Hello');">Hello</p>
870 * @param Function fn A function to bind to the mousedown event on each of the matched elements.
873 jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
874 "mousedown,mouseup,mousemove,mouseover,mouseout,change,select," +
875 "submit,keydown,keypress,keyup,error").split(","), function(i,o){
877 // Handle event binding
878 jQuery.fn[o] = function(f){
879 return f ? this.bind(o, f) : this.trigger(o);
884 // If Mozilla is used
885 if ( jQuery.browser.mozilla || jQuery.browser.opera )
886 // Use the handy event callback
887 document.addEventListener( "DOMContentLoaded", jQuery.ready, false );
889 // If IE is used, use the excellent hack by Matthias Miller
890 // http://www.outofhanwell.com/blog/index.php?title=the_window_onload_problem_revisited
891 else if ( jQuery.browser.msie ) {
893 // Only works if you document.write() it
894 document.write("<scr" + "ipt id=__ie_init defer=true " +
895 "src=//:><\/script>");
897 // Use the defer script hack
898 var script = document.getElementById("__ie_init");
900 // script does not exist if jQuery is loaded dynamically
902 script.onreadystatechange = function() {
903 if ( this.readyState != "complete" ) return;
904 this.parentNode.removeChild( this );
912 } else if ( jQuery.browser.safari )
913 // Continually check to see if the document.readyState is valid
914 jQuery.safariTimer = setInterval(function(){
915 // loaded and complete are both valid states
916 if ( document.readyState == "loaded" ||
917 document.readyState == "complete" ) {
919 // If either one are found, remove the timer
920 clearInterval( jQuery.safariTimer );
921 jQuery.safariTimer = null;
923 // and execute any waiting functions
928 // A fallback to window.onload, that will always work
929 jQuery.event.add( window, "load", jQuery.ready );
933 // Clean up after IE to avoid memory leaks
934 if (jQuery.browser.msie)
935 jQuery(window).one("unload", function() {
936 var global = jQuery.event.global;
937 for ( var type in global ) {
938 var els = global[type], i = els.length;
939 if ( i && type != 'unload' )
941 jQuery.event.remove(els[i-1], type);