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 paramter (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.
330 * @example $("p").trigger("click")
331 * @before <p click="alert('hello')">Hello</p>
332 * @result alert('hello')
334 * @example $("p").click(function(event, a, b) {
335 * // when a normal click fires, a and b are undefined
336 * // for a trigger like below a refers too "foo" and b refers to "bar"
337 * }).trigger("click", ["foo", "bar"]);
338 * @desc Example of how to pass arbitrary to an event
340 * @before <p click="alert('hello')">Hello</p>
341 * @result alert('hello')
345 * @param String type An event type to trigger.
346 * @param Array data (optional) Additional data to pass as arguments (after the event object) to the event handler
349 trigger: function( type, data ) {
350 return this.each(function(){
351 jQuery.event.trigger( type, data, this );
356 * Toggle between two function calls every other click.
357 * Whenever a matched element is clicked, the first specified function
358 * is fired, when clicked again, the second is fired. All subsequent
359 * clicks continue to rotate through the two functions.
361 * Use unbind("click") to remove.
363 * @example $("p").toggle(function(){
364 * $(this).addClass("selected");
366 * $(this).removeClass("selected");
371 * @param Function even The function to execute on every even click.
372 * @param Function odd The function to execute on every odd click.
376 // Save reference to arguments for access in closure
379 return this.click(function(e) {
380 // Figure out which function to execute
381 this.lastToggle = this.lastToggle == 0 ? 1 : 0;
383 // Make sure that clicks stop
386 // and execute the function
387 return a[this.lastToggle].apply( this, [e] ) || false;
392 * A method for simulating hovering (moving the mouse on, and off,
393 * an object). This is a custom method which provides an 'in' to a
396 * Whenever the mouse cursor is moved over a matched
397 * element, the first specified function is fired. Whenever the mouse
398 * moves off of the element, the second specified function fires.
399 * Additionally, checks are in place to see if the mouse is still within
400 * the specified element itself (for example, an image inside of a div),
401 * and if it is, it will continue to 'hover', and not move out
402 * (a common error in using a mouseout event handler).
404 * @example $("p").hover(function(){
405 * $(this).addClass("over");
407 * $(this).addClass("out");
412 * @param Function over The function to fire whenever the mouse is moved over a matched element.
413 * @param Function out The function to fire whenever the mouse is moved off of a matched element.
416 hover: function(f,g) {
418 // A private function for handling mouse 'hovering'
419 function handleHover(e) {
420 // Check if mouse(over|out) are still within the same parent element
421 var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
423 // Traverse up the tree
424 while ( p && p != this ) try { p = p.parentNode } catch(e) { p = this; };
426 // If we actually just moused on to a sub-element, ignore it
427 if ( p == this ) return false;
429 // Execute the right function
430 return (e.type == "mouseover" ? f : g).apply(this, [e]);
433 // Bind the function to the two event listeners
434 return this.mouseover(handleHover).mouseout(handleHover);
438 * Bind a function to be executed whenever the DOM is ready to be
439 * traversed and manipulated. This is probably the most important
440 * function included in the event module, as it can greatly improve
441 * the response times of your web applications.
443 * In a nutshell, this is a solid replacement for using window.onload,
444 * and attaching a function to that. By using this method, your bound Function
445 * will be called the instant the DOM is ready to be read and manipulated,
446 * which is exactly what 99.99% of all Javascript code needs to run.
448 * There is one argument passed to the ready event handler: A reference to
449 * the jQuery function. You can name that argument whatever you like, and
450 * can therefore stick with the $ alias without risk of naming collisions.
452 * Please ensure you have no code in your <body> onload event handler,
453 * otherwise $(document).ready() may not fire.
455 * You can have as many $(document).ready events on your page as you like.
456 * The functions are then executed in the order they were added.
458 * @example $(document).ready(function(){ Your code here... });
460 * @example jQuery(function($) {
461 * // Your code using failsafe $ alias here...
463 * @desc Uses both the shortcut for $(document).ready() and the argument
464 * to write failsafe jQuery code using the $ alias, without relying on the
469 * @param Function fn The function to be executed when the DOM is ready.
471 * @see $.noConflict()
475 // If the DOM is already ready
476 if ( jQuery.isReady )
477 // Execute the function immediately
478 f.apply( document, [jQuery] );
480 // Otherwise, remember the function for later
482 // Add the function to the wait list
483 jQuery.readyList.push( function() { return f.apply(this, [jQuery]) } );
492 * All the code that makes DOM Ready work nicely.
497 // Handle when the DOM is ready
499 // Make sure that the DOM is not already loaded
500 if ( !jQuery.isReady ) {
501 // Remember that the DOM is ready
502 jQuery.isReady = true;
504 // If there are functions bound, to execute
505 if ( jQuery.readyList ) {
506 // Execute all of them
507 jQuery.each( jQuery.readyList, function(){
508 this.apply( document );
511 // Reset the list of functions
512 jQuery.readyList = null;
514 // Remove event lisenter to avoid memory leak
515 if ( jQuery.browser.mozilla || jQuery.browser.opera )
516 document.removeEventListener( "DOMContentLoaded", jQuery.ready, false );
524 * Bind a function to the scroll event of each matched element.
526 * @example $("p").scroll( function() { alert("Hello"); } );
527 * @before <p>Hello</p>
528 * @result <p onscroll="alert('Hello');">Hello</p>
532 * @param Function fn A function to bind to the scroll event on each of the matched elements.
537 * Bind a function to the submit event of each matched element.
539 * @example $("#myform").submit( function() {
540 * return $("input", this).val().length > 0;
542 * @before <form id="myform"><input /></form>
543 * @desc Prevents the form submission when the input has no value entered.
547 * @param Function fn A function to bind to the submit event on each of the matched elements.
552 * Trigger the submit event of each matched element. This causes all of the functions
553 * that have been bound to thet submit event to be executed.
555 * Note: This does not execute the submit method of the form element! If you need to
556 * submit the form via code, you have to use the DOM method, eg. $("form")[0].submit();
558 * @example $("form").submit();
559 * @desc Triggers all submit events registered for forms, but does not submit the form
567 * Bind a function to the focus event of each matched element.
569 * @example $("p").focus( function() { alert("Hello"); } );
570 * @before <p>Hello</p>
571 * @result <p onfocus="alert('Hello');">Hello</p>
575 * @param Function fn A function to bind to the focus event on each of the matched elements.
580 * Trigger the focus event of each matched element. This causes all of the functions
581 * that have been bound to thet focus event to be executed.
583 * Note: This does not execute the focus method of the underlying elements! If you need to
584 * focus an element via code, you have to use the DOM method, eg. $("#myinput")[0].focus();
586 * @example $("p").focus();
587 * @before <p onfocus="alert('Hello');">Hello</p>
588 * @result alert('Hello');
596 * Bind a function to the keydown event of each matched element.
598 * @example $("p").keydown( function() { alert("Hello"); } );
599 * @before <p>Hello</p>
600 * @result <p onkeydown="alert('Hello');">Hello</p>
604 * @param Function fn A function to bind to the keydown event on each of the matched elements.
609 * Bind a function to the dblclick event of each matched element.
611 * @example $("p").dblclick( function() { alert("Hello"); } );
612 * @before <p>Hello</p>
613 * @result <p ondblclick="alert('Hello');">Hello</p>
617 * @param Function fn A function to bind to the dblclick event on each of the matched elements.
622 * Bind a function to the keypress event of each matched element.
624 * @example $("p").keypress( function() { alert("Hello"); } );
625 * @before <p>Hello</p>
626 * @result <p onkeypress="alert('Hello');">Hello</p>
630 * @param Function fn A function to bind to the keypress event on each of the matched elements.
635 * Bind a function to the error event of each matched element.
637 * @example $("p").error( function() { alert("Hello"); } );
638 * @before <p>Hello</p>
639 * @result <p onerror="alert('Hello');">Hello</p>
643 * @param Function fn A function to bind to the error event on each of the matched elements.
648 * Bind a function to the blur event of each matched element.
650 * @example $("p").blur( function() { alert("Hello"); } );
651 * @before <p>Hello</p>
652 * @result <p onblur="alert('Hello');">Hello</p>
656 * @param Function fn A function to bind to the blur event on each of the matched elements.
661 * Trigger the blur event of each matched element. This causes all of the functions
662 * that have been bound to thet blur event to be executed.
664 * Note: This does not execute the blur method of the underlying elements! If you need to
665 * blur an element via code, you have to use the DOM method, eg. $("#myinput")[0].blur();
667 * @example $("p").blur();
668 * @before <p onblur="alert('Hello');">Hello</p>
669 * @result alert('Hello');
677 * Bind a function to the load event of each matched element.
679 * @example $("p").load( function() { alert("Hello"); } );
680 * @before <p>Hello</p>
681 * @result <p onload="alert('Hello');">Hello</p>
685 * @param Function fn A function to bind to the load event on each of the matched elements.
690 * Bind a function to the select event of each matched element.
692 * @example $("p").select( function() { alert("Hello"); } );
693 * @before <p>Hello</p>
694 * @result <p onselect="alert('Hello');">Hello</p>
698 * @param Function fn A function to bind to the select event on each of the matched elements.
703 * Trigger the select event of each matched element. This causes all of the functions
704 * that have been bound to thet select event to be executed.
706 * @example $("p").select();
707 * @before <p onselect="alert('Hello');">Hello</p>
708 * @result alert('Hello');
716 * Bind a function to the mouseup event of each matched element.
718 * @example $("p").mouseup( function() { alert("Hello"); } );
719 * @before <p>Hello</p>
720 * @result <p onmouseup="alert('Hello');">Hello</p>
724 * @param Function fn A function to bind to the mouseup event on each of the matched elements.
729 * Bind a function to the unload event of each matched element.
731 * @example $("p").unload( function() { alert("Hello"); } );
732 * @before <p>Hello</p>
733 * @result <p onunload="alert('Hello');">Hello</p>
737 * @param Function fn A function to bind to the unload event on each of the matched elements.
742 * Bind a function to the change event of each matched element.
744 * @example $("p").change( function() { alert("Hello"); } );
745 * @before <p>Hello</p>
746 * @result <p onchange="alert('Hello');">Hello</p>
750 * @param Function fn A function to bind to the change event on each of the matched elements.
755 * Bind a function to the mouseout event of each matched element.
757 * @example $("p").mouseout( function() { alert("Hello"); } );
758 * @before <p>Hello</p>
759 * @result <p onmouseout="alert('Hello');">Hello</p>
763 * @param Function fn A function to bind to the mouseout event on each of the matched elements.
768 * Bind a function to the keyup event of each matched element.
770 * @example $("p").keyup( function() { alert("Hello"); } );
771 * @before <p>Hello</p>
772 * @result <p onkeyup="alert('Hello');">Hello</p>
776 * @param Function fn A function to bind to the keyup event on each of the matched elements.
781 * Bind a function to the click event of each matched element.
783 * @example $("p").click( function() { alert("Hello"); } );
784 * @before <p>Hello</p>
785 * @result <p onclick="alert('Hello');">Hello</p>
789 * @param Function fn A function to bind to the click event on each of the matched elements.
794 * Trigger the click event of each matched element. This causes all of the functions
795 * that have been bound to thet click event to be executed.
797 * @example $("p").click();
798 * @before <p onclick="alert('Hello');">Hello</p>
799 * @result alert('Hello');
807 * Bind a function to the resize event of each matched element.
809 * @example $("p").resize( function() { alert("Hello"); } );
810 * @before <p>Hello</p>
811 * @result <p onresize="alert('Hello');">Hello</p>
815 * @param Function fn A function to bind to the resize event on each of the matched elements.
820 * Bind a function to the mousemove event of each matched element.
822 * @example $("p").mousemove( function() { alert("Hello"); } );
823 * @before <p>Hello</p>
824 * @result <p onmousemove="alert('Hello');">Hello</p>
828 * @param Function fn A function to bind to the mousemove event on each of the matched elements.
833 * Bind a function to the mousedown event of each matched element.
835 * @example $("p").mousedown( function() { alert("Hello"); } );
836 * @before <p>Hello</p>
837 * @result <p onmousedown="alert('Hello');">Hello</p>
841 * @param Function fn A function to bind to the mousedown event on each of the matched elements.
846 * Bind a function to the mouseover event of each matched element.
848 * @example $("p").mouseover( function() { alert("Hello"); } );
849 * @before <p>Hello</p>
850 * @result <p onmouseover="alert('Hello');">Hello</p>
854 * @param Function fn A function to bind to the mousedown event on each of the matched elements.
857 jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
858 "mousedown,mouseup,mousemove,mouseover,mouseout,change,select," +
859 "submit,keydown,keypress,keyup,error").split(","), function(i,o){
861 // Handle event binding
862 jQuery.fn[o] = function(f){
863 return f ? this.bind(o, f) : this.trigger(o);
868 // If Mozilla is used
869 if ( jQuery.browser.mozilla || jQuery.browser.opera )
870 // Use the handy event callback
871 document.addEventListener( "DOMContentLoaded", jQuery.ready, false );
873 // If IE is used, use the excellent hack by Matthias Miller
874 // http://www.outofhanwell.com/blog/index.php?title=the_window_onload_problem_revisited
875 else if ( jQuery.browser.msie ) {
877 // Only works if you document.write() it
878 document.write("<scr" + "ipt id=__ie_init defer=true " +
879 "src=//:><\/script>");
881 // Use the defer script hack
882 var script = document.getElementById("__ie_init");
884 // script does not exist if jQuery is loaded dynamically
886 script.onreadystatechange = function() {
887 if ( this.readyState != "complete" ) return;
888 this.parentNode.removeChild( this );
896 } else if ( jQuery.browser.safari )
897 // Continually check to see if the document.readyState is valid
898 jQuery.safariTimer = setInterval(function(){
899 // loaded and complete are both valid states
900 if ( document.readyState == "loaded" ||
901 document.readyState == "complete" ) {
903 // If either one are found, remove the timer
904 clearInterval( jQuery.safariTimer );
905 jQuery.safariTimer = null;
907 // and execute any waiting functions
912 // A fallback to window.onload, that will always work
913 jQuery.event.add( window, "load", jQuery.ready );
917 // Clean up after IE to avoid memory leaks
918 if (jQuery.browser.msie)
919 jQuery(window).one("unload", function() {
920 var global = jQuery.event.global;
921 for ( var type in global ) {
922 var els = global[type], i = els.length;
923 if ( i && type != 'unload' )
925 jQuery.event.remove(els[i-1], type);