2 * A number of helper functions used for managing events.
3 * Many of the ideas behind this code orignated from
4 * Dean Edwards' addEvent library.
8 // Bind an event to an element
9 // Original by Dean Edwards
10 add: function(element, type, handler, data) {
11 // For whatever reason, IE has trouble passing the window object
12 // around, causing it to be cloned in the process
13 if ( jQuery.browser.msie && element.setInterval != undefined )
16 // if data is passed, bind to handler
20 // Make sure that the function being executed has a unique ID
22 handler.guid = this.guid++;
24 // Init the element's event structure
28 // Get the current list of functions bound to this event
29 var handlers = element.events[type];
31 // If it hasn't been initialized yet
33 // Init the event handler queue
34 handlers = element.events[type] = {};
36 // Remember an existing handler, if it's already there
37 if (element["on" + type])
38 handlers[0] = element["on" + type];
41 // Add the function to the element's handler list
42 handlers[handler.guid] = handler;
44 // And bind the global event handler to the element
45 element["on" + type] = this.handle;
47 // Remember the function in a global list (for triggering)
48 if (!this.global[type])
49 this.global[type] = [];
50 this.global[type].push( element );
56 // Detach an event or set of events from an element
57 remove: function(element, type, handler) {
59 if ( type && type.type )
60 delete element.events[ type.type ][ type.handler.guid ];
61 else if (type && element.events[type])
63 delete element.events[type][handler.guid];
65 for ( var i in element.events[type] )
66 delete element.events[type][i];
68 for ( var j in element.events )
69 this.remove( element, j );
72 trigger: function(type,data,element) {
73 // Clone the incoming data, if any
74 data = jQuery.makeArray(data || []);
76 // Handle a global trigger
78 jQuery.each( this.global[type] || [], function(){
79 jQuery.event.trigger( type, data, this );
82 // Handle triggering a single element
83 else if ( element["on" + type] ) {
84 // Pass along a fake event
85 data.unshift( this.fix({ type: type, target: element }) );
88 var val = element["on" + type].apply( element, data );
90 if ( val !== false && jQuery.isFunction( element[ type ] ) ) {
91 this.triggered = true;
94 } else if ( jQuery.isFunction( element[ type ] ) )
98 handle: function(event) {
99 if ( typeof jQuery == "undefined" ) return;
101 // Handle the second event of a trigger
102 if ( jQuery.event.triggered ) {
103 jQuery.event.triggered = false;
107 // Empty object is for triggered events with no data
108 event = jQuery.event.fix( event || window.event || {} );
110 // returned undefined or false
113 var c = this.events[event.type];
115 var args = [].slice.call( arguments, 1 );
116 args.unshift( event );
119 // Pass in a reference to the handler function itself
120 // So that we can later remove it
121 args[0].handler = c[j];
122 args[0].data = c[j].data;
124 if ( c[j].apply( this, args ) === false ) {
125 event.preventDefault();
126 event.stopPropagation();
131 // Clean up added properties in IE to prevent memory leak
132 if (jQuery.browser.msie) event.target = event.preventDefault = event.stopPropagation = event.handler = event.data = null;
137 fix: function(event) {
138 // Fix target property, if necessary
139 if ( !event.target && event.srcElement )
140 event.target = event.srcElement;
142 // Calculate pageX/Y if missing and clientX/Y available
143 if ( event.pageX == undefined && event.clientX != undefined ) {
144 var e = document.documentElement, b = document.body;
145 event.pageX = event.clientX + (e.scrollLeft || b.scrollLeft);
146 event.pageY = event.clientY + (e.scrollTop || b.scrollTop);
149 // check if target is a textnode (safari)
150 if (jQuery.browser.safari && event.target.nodeType == 3) {
151 // store a copy of the original event object
152 // and clone because target is read only
153 var originalEvent = event;
154 event = jQuery.extend({}, originalEvent);
156 // get parentnode from textnode
157 event.target = originalEvent.target.parentNode;
159 // add preventDefault and stopPropagation since
160 // they will not work on the clone
161 event.preventDefault = function() {
162 return originalEvent.preventDefault();
164 event.stopPropagation = function() {
165 return originalEvent.stopPropagation();
169 // fix preventDefault and stopPropagation
170 if (!event.preventDefault)
171 event.preventDefault = function() {
172 this.returnValue = false;
175 if (!event.stopPropagation)
176 event.stopPropagation = function() {
177 this.cancelBubble = true;
187 * Binds a handler to a particular event (like click) for each matched element.
188 * The event handler is passed an event object that you can use to prevent
189 * default behaviour. To stop both default action and event bubbling, your handler
190 * has to return false.
192 * In most cases, you can define your event handlers as anonymous functions
193 * (see first example). In cases where that is not possible, you can pass additional
194 * data as the second paramter (and the handler function as the third), see
197 * @example $("p").bind("click", function(){
198 * alert( $(this).text() );
200 * @before <p>Hello</p>
201 * @result alert("Hello")
203 * @example function handler(event) {
204 * alert(event.data.foo);
206 * $("p").bind("click", {foo: "bar"}, handler)
207 * @result alert("bar")
208 * @desc Pass some additional data to the event handler.
210 * @example $("form").bind("submit", function() { return false; })
211 * @desc Cancel a default action and prevent it from bubbling by returning false
212 * from your function.
214 * @example $("form").bind("submit", function(event){
215 * event.preventDefault();
217 * @desc Cancel only the default action by using the preventDefault method.
220 * @example $("form").bind("submit", function(event){
221 * event.stopPropagation();
223 * @desc Stop only an event from bubbling by using the stopPropagation method.
227 * @param String type An event type
228 * @param Object data (optional) Additional data passed to the event handler as event.data
229 * @param Function fn A function to bind to the event on each of the set of matched elements
232 bind: function( type, data, fn ) {
233 return this.each(function(){
234 jQuery.event.add( this, type, fn || data, data );
239 * Binds a handler to a particular event (like click) for each matched element.
240 * The handler is executed only once for each element. Otherwise, the same rules
241 * as described in bind() apply.
242 The event handler is passed an event object that you can use to prevent
243 * default behaviour. To stop both default action and event bubbling, your handler
244 * has to return false.
246 * In most cases, you can define your event handlers as anonymous functions
247 * (see first example). In cases where that is not possible, you can pass additional
248 * data as the second paramter (and the handler function as the third), see
251 * @example $("p").one("click", function(){
252 * alert( $(this).text() );
254 * @before <p>Hello</p>
255 * @result alert("Hello")
259 * @param String type An event type
260 * @param Object data (optional) Additional data passed to the event handler as event.data
261 * @param Function fn A function to bind to the event on each of the set of matched elements
264 one: function( type, data, fn ) {
265 return this.each(function(){
266 jQuery.event.add( this, type, function(event) {
267 jQuery(this).unbind(event);
268 return (fn || data).apply( this, arguments);
274 * The opposite of bind, removes a bound event from each of the matched
277 * Without any arguments, all bound events are removed.
279 * If the type is provided, all bound events of that type are removed.
281 * If the function that was passed to bind is provided as the second argument,
282 * only that specific event handler is removed.
284 * @example $("p").unbind()
285 * @before <p onclick="alert('Hello');">Hello</p>
286 * @result [ <p>Hello</p> ]
288 * @example $("p").unbind( "click" )
289 * @before <p onclick="alert('Hello');">Hello</p>
290 * @result [ <p>Hello</p> ]
292 * @example $("p").unbind( "click", function() { alert("Hello"); } )
293 * @before <p onclick="alert('Hello');">Hello</p>
294 * @result [ <p>Hello</p> ]
298 * @param String type (optional) An event type
299 * @param Function fn (optional) A function to unbind from the event on each of the set of matched elements
302 unbind: function( type, fn ) {
303 return this.each(function(){
304 jQuery.event.remove( this, type, fn );
309 * Trigger a type of event on every matched element.
311 * @example $("p").trigger("click")
312 * @before <p click="alert('hello')">Hello</p>
313 * @result alert('hello')
317 * @param String type An event type to trigger.
320 trigger: function( type, data ) {
321 return this.each(function(){
322 jQuery.event.trigger( type, data, this );
327 * Toggle between two function calls every other click.
328 * Whenever a matched element is clicked, the first specified function
329 * is fired, when clicked again, the second is fired. All subsequent
330 * clicks continue to rotate through the two functions.
332 * Use unbind("click") to remove.
334 * @example $("p").toggle(function(){
335 * $(this).addClass("selected");
337 * $(this).removeClass("selected");
342 * @param Function even The function to execute on every even click.
343 * @param Function odd The function to execute on every odd click.
347 // Save reference to arguments for access in closure
350 return this.click(function(e) {
351 // Figure out which function to execute
352 this.lastToggle = this.lastToggle == 0 ? 1 : 0;
354 // Make sure that clicks stop
357 // and execute the function
358 return a[this.lastToggle].apply( this, [e] ) || false;
363 * A method for simulating hovering (moving the mouse on, and off,
364 * an object). This is a custom method which provides an 'in' to a
367 * Whenever the mouse cursor is moved over a matched
368 * element, the first specified function is fired. Whenever the mouse
369 * moves off of the element, the second specified function fires.
370 * Additionally, checks are in place to see if the mouse is still within
371 * the specified element itself (for example, an image inside of a div),
372 * and if it is, it will continue to 'hover', and not move out
373 * (a common error in using a mouseout event handler).
375 * @example $("p").hover(function(){
376 * $(this).addClass("over");
378 * $(this).addClass("out");
383 * @param Function over The function to fire whenever the mouse is moved over a matched element.
384 * @param Function out The function to fire whenever the mouse is moved off of a matched element.
387 hover: function(f,g) {
389 // A private function for handling mouse 'hovering'
390 function handleHover(e) {
391 // Check if mouse(over|out) are still within the same parent element
392 var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
394 // Traverse up the tree
395 while ( p && p != this ) try { p = p.parentNode } catch(e) { p = this; };
397 // If we actually just moused on to a sub-element, ignore it
398 if ( p == this ) return false;
400 // Execute the right function
401 return (e.type == "mouseover" ? f : g).apply(this, [e]);
404 // Bind the function to the two event listeners
405 return this.mouseover(handleHover).mouseout(handleHover);
409 * Bind a function to be executed whenever the DOM is ready to be
410 * traversed and manipulated. This is probably the most important
411 * function included in the event module, as it can greatly improve
412 * the response times of your web applications.
414 * In a nutshell, this is a solid replacement for using window.onload,
415 * and attaching a function to that. By using this method, your bound Function
416 * will be called the instant the DOM is ready to be read and manipulated,
417 * which is exactly what 99.99% of all Javascript code needs to run.
419 * There is one argument passed to the ready event handler: A reference to
420 * the jQuery function. You can name that argument whatever you like, and
421 * can therefore stick with the $ alias without risc of naming collisions.
423 * Please ensure you have no code in your <body> onload event handler,
424 * otherwise $(document).ready() may not fire.
426 * You can have as many $(document).ready events on your page as you like.
427 * The functions are then executed in the order they were added.
429 * @example $(document).ready(function(){ Your code here... });
431 * @example jQuery(function($) {
432 * // Your code using failsafe $ alias here...
434 * @desc Uses both the shortcut for $(document).ready() and the argument
435 * to write failsafe jQuery code using the $ alias, without relying on the
440 * @param Function fn The function to be executed when the DOM is ready.
442 * @see $.noConflict()
446 // If the DOM is already ready
447 if ( jQuery.isReady )
448 // Execute the function immediately
449 f.apply( document, [jQuery] );
451 // Otherwise, remember the function for later
453 // Add the function to the wait list
454 jQuery.readyList.push( function() { return f.apply(this, [jQuery]) } );
463 * All the code that makes DOM Ready work nicely.
468 // Handle when the DOM is ready
470 // Make sure that the DOM is not already loaded
471 if ( !jQuery.isReady ) {
472 // Remember that the DOM is ready
473 jQuery.isReady = true;
475 // If there are functions bound, to execute
476 if ( jQuery.readyList ) {
477 // Execute all of them
478 jQuery.each( jQuery.readyList, function(){
479 this.apply( document );
482 // Reset the list of functions
483 jQuery.readyList = null;
485 // Remove event lisenter to avoid memory leak
486 if ( jQuery.browser.mozilla || jQuery.browser.opera )
487 document.removeEventListener( "DOMContentLoaded", jQuery.ready, false );
495 * Bind a function to the scroll event of each matched element.
497 * @example $("p").scroll( function() { alert("Hello"); } );
498 * @before <p>Hello</p>
499 * @result <p onscroll="alert('Hello');">Hello</p>
503 * @param Function fn A function to bind to the scroll event on each of the matched elements.
508 * Bind a function to the submit event of each matched element.
510 * @example $("#myform").submit( function() {
511 * return $("input", this).val().length > 0;
513 * @before <form id="myform"><input /></form>
514 * @desc Prevents the form submission when the input has no value entered.
518 * @param Function fn A function to bind to the submit event on each of the matched elements.
523 * Trigger the submit event of each matched element. This causes all of the functions
524 * that have been bound to thet submit event to be executed.
526 * Note: This does not execute the submit method of the form element! If you need to
527 * submit the form via code, you have to use the DOM method, eg. $("form")[0].submit();
529 * @example $("form").submit();
530 * @desc Triggers all submit events registered for forms, but does not submit the form
538 * Bind a function to the focus event of each matched element.
540 * @example $("p").focus( function() { alert("Hello"); } );
541 * @before <p>Hello</p>
542 * @result <p onfocus="alert('Hello');">Hello</p>
546 * @param Function fn A function to bind to the focus event on each of the matched elements.
551 * Trigger the focus event of each matched element. This causes all of the functions
552 * that have been bound to thet focus event to be executed.
554 * Note: This does not execute the focus method of the underlying elements! If you need to
555 * focus an element via code, you have to use the DOM method, eg. $("#myinput")[0].focus();
557 * @example $("p").focus();
558 * @before <p onfocus="alert('Hello');">Hello</p>
559 * @result alert('Hello');
567 * Bind a function to the keydown event of each matched element.
569 * @example $("p").keydown( function() { alert("Hello"); } );
570 * @before <p>Hello</p>
571 * @result <p onkeydown="alert('Hello');">Hello</p>
575 * @param Function fn A function to bind to the keydown event on each of the matched elements.
580 * Bind a function to the dblclick event of each matched element.
582 * @example $("p").dblclick( function() { alert("Hello"); } );
583 * @before <p>Hello</p>
584 * @result <p ondblclick="alert('Hello');">Hello</p>
588 * @param Function fn A function to bind to the dblclick event on each of the matched elements.
593 * Bind a function to the keypress event of each matched element.
595 * @example $("p").keypress( function() { alert("Hello"); } );
596 * @before <p>Hello</p>
597 * @result <p onkeypress="alert('Hello');">Hello</p>
601 * @param Function fn A function to bind to the keypress event on each of the matched elements.
606 * Bind a function to the error event of each matched element.
608 * @example $("p").error( function() { alert("Hello"); } );
609 * @before <p>Hello</p>
610 * @result <p onerror="alert('Hello');">Hello</p>
614 * @param Function fn A function to bind to the error event on each of the matched elements.
619 * Bind a function to the blur event of each matched element.
621 * @example $("p").blur( function() { alert("Hello"); } );
622 * @before <p>Hello</p>
623 * @result <p onblur="alert('Hello');">Hello</p>
627 * @param Function fn A function to bind to the blur event on each of the matched elements.
632 * Trigger the blur event of each matched element. This causes all of the functions
633 * that have been bound to thet blur event to be executed.
635 * Note: This does not execute the blur method of the underlying elements! If you need to
636 * blur an element via code, you have to use the DOM method, eg. $("#myinput")[0].blur();
638 * @example $("p").blur();
639 * @before <p onblur="alert('Hello');">Hello</p>
640 * @result alert('Hello');
648 * Bind a function to the load event of each matched element.
650 * @example $("p").load( function() { alert("Hello"); } );
651 * @before <p>Hello</p>
652 * @result <p onload="alert('Hello');">Hello</p>
656 * @param Function fn A function to bind to the load event on each of the matched elements.
661 * Bind a function to the select event of each matched element.
663 * @example $("p").select( function() { alert("Hello"); } );
664 * @before <p>Hello</p>
665 * @result <p onselect="alert('Hello');">Hello</p>
669 * @param Function fn A function to bind to the select event on each of the matched elements.
674 * Trigger the select event of each matched element. This causes all of the functions
675 * that have been bound to thet select event to be executed.
677 * @example $("p").select();
678 * @before <p onselect="alert('Hello');">Hello</p>
679 * @result alert('Hello');
687 * Bind a function to the mouseup event of each matched element.
689 * @example $("p").mouseup( function() { alert("Hello"); } );
690 * @before <p>Hello</p>
691 * @result <p onmouseup="alert('Hello');">Hello</p>
695 * @param Function fn A function to bind to the mouseup event on each of the matched elements.
700 * Bind a function to the unload event of each matched element.
702 * @example $("p").unload( function() { alert("Hello"); } );
703 * @before <p>Hello</p>
704 * @result <p onunload="alert('Hello');">Hello</p>
708 * @param Function fn A function to bind to the unload event on each of the matched elements.
713 * Bind a function to the change event of each matched element.
715 * @example $("p").change( function() { alert("Hello"); } );
716 * @before <p>Hello</p>
717 * @result <p onchange="alert('Hello');">Hello</p>
721 * @param Function fn A function to bind to the change event on each of the matched elements.
726 * Bind a function to the mouseout event of each matched element.
728 * @example $("p").mouseout( function() { alert("Hello"); } );
729 * @before <p>Hello</p>
730 * @result <p onmouseout="alert('Hello');">Hello</p>
734 * @param Function fn A function to bind to the mouseout event on each of the matched elements.
739 * Bind a function to the keyup event of each matched element.
741 * @example $("p").keyup( function() { alert("Hello"); } );
742 * @before <p>Hello</p>
743 * @result <p onkeyup="alert('Hello');">Hello</p>
747 * @param Function fn A function to bind to the keyup event on each of the matched elements.
752 * Bind a function to the click event of each matched element.
754 * @example $("p").click( function() { alert("Hello"); } );
755 * @before <p>Hello</p>
756 * @result <p onclick="alert('Hello');">Hello</p>
760 * @param Function fn A function to bind to the click event on each of the matched elements.
765 * Trigger the click event of each matched element. This causes all of the functions
766 * that have been bound to thet click event to be executed.
768 * @example $("p").click();
769 * @before <p onclick="alert('Hello');">Hello</p>
770 * @result alert('Hello');
778 * Bind a function to the resize event of each matched element.
780 * @example $("p").resize( function() { alert("Hello"); } );
781 * @before <p>Hello</p>
782 * @result <p onresize="alert('Hello');">Hello</p>
786 * @param Function fn A function to bind to the resize event on each of the matched elements.
791 * Bind a function to the mousemove event of each matched element.
793 * @example $("p").mousemove( function() { alert("Hello"); } );
794 * @before <p>Hello</p>
795 * @result <p onmousemove="alert('Hello');">Hello</p>
799 * @param Function fn A function to bind to the mousemove event on each of the matched elements.
804 * Bind a function to the mousedown event of each matched element.
806 * @example $("p").mousedown( function() { alert("Hello"); } );
807 * @before <p>Hello</p>
808 * @result <p onmousedown="alert('Hello');">Hello</p>
812 * @param Function fn A function to bind to the mousedown event on each of the matched elements.
817 * Bind a function to the mouseover event of each matched element.
819 * @example $("p").mouseover( function() { alert("Hello"); } );
820 * @before <p>Hello</p>
821 * @result <p onmouseover="alert('Hello');">Hello</p>
825 * @param Function fn A function to bind to the mousedown event on each of the matched elements.
828 jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
829 "mousedown,mouseup,mousemove,mouseover,mouseout,change,select," +
830 "submit,keydown,keypress,keyup,error").split(","), function(i,o){
832 // Handle event binding
833 jQuery.fn[o] = function(f){
834 return f ? this.bind(o, f) : this.trigger(o);
839 // If Mozilla is used
840 if ( jQuery.browser.mozilla || jQuery.browser.opera )
841 // Use the handy event callback
842 document.addEventListener( "DOMContentLoaded", jQuery.ready, false );
844 // If IE is used, use the excellent hack by Matthias Miller
845 // http://www.outofhanwell.com/blog/index.php?title=the_window_onload_problem_revisited
846 else if ( jQuery.browser.msie ) {
848 // Only works if you document.write() it
849 document.write("<scr" + "ipt id=__ie_init defer=true " +
850 "src=//:><\/script>");
852 // Use the defer script hack
853 var script = document.getElementById("__ie_init");
855 // script does not exist if jQuery is loaded dynamically
857 script.onreadystatechange = function() {
858 if ( this.readyState != "complete" ) return;
859 this.parentNode.removeChild( this );
867 } else if ( jQuery.browser.safari )
868 // Continually check to see if the document.readyState is valid
869 jQuery.safariTimer = setInterval(function(){
870 // loaded and complete are both valid states
871 if ( document.readyState == "loaded" ||
872 document.readyState == "complete" ) {
874 // If either one are found, remove the timer
875 clearInterval( jQuery.safariTimer );
876 jQuery.safariTimer = null;
878 // and execute any waiting functions
883 // A fallback to window.onload, that will always work
884 jQuery.event.add( window, "load", jQuery.ready );
888 // Clean up after IE to avoid memory leaks
889 if (jQuery.browser.msie)
890 jQuery(window).one("unload", function() {
891 var global = jQuery.event.global;
892 for ( var type in global ) {
893 var els = global[type], i = els.length;
894 if ( i && type != 'unload' )
896 jQuery.event.remove(els[i-1], type);