4 * Copyright(c) 2006-2007, Ext JS, LLC.
6 * Originally Released Under LGPL - original licence link has changed is not relivant.
9 * <script type="text/javascript">
13 * @class Roo.EventManager
14 * Registers event handlers that want to receive a normalized EventObject instead of the standard browser event and provides
15 * several useful events directly.
16 * See {@link Roo.EventObject} for more details on normalized event objects.
19 Roo.EventManager = function(){
20 var docReadyEvent, docReadyProcId, docReadyState = false;
21 var resizeEvent, resizeTask, textEvent, textSize;
22 var E = Roo.lib.Event;
25 var transEndEventNames = {
26 WebkitTransition : 'webkitTransitionEnd',
27 MozTransition : 'transitionend',
28 OTransition : 'oTransitionEnd otransitionend',
29 transition : 'transitionend'
33 var fireDocReady = function(){
38 clearInterval(docReadyProcId);
40 if(Roo.isGecko || Roo.isOpera) {
41 document.removeEventListener("DOMContentLoaded", fireDocReady, false);
44 var defer = document.getElementById("ie-deferred-loader");
46 defer.onreadystatechange = null;
47 defer.parentNode.removeChild(defer);
52 docReadyEvent.clearListeners();
57 var initDocReady = function(){
58 docReadyEvent = new Roo.util.Event();
59 if(Roo.isGecko || Roo.isOpera) {
60 document.addEventListener("DOMContentLoaded", fireDocReady, false);
62 document.write("<s"+'cript id="ie-deferred-loader" defer="defer" src="/'+'/:"></s'+"cript>");
63 var defer = document.getElementById("ie-deferred-loader");
64 defer.onreadystatechange = function(){
65 if(this.readyState == "complete"){
69 }else if(Roo.isSafari){
70 docReadyProcId = setInterval(function(){
71 var rs = document.readyState;
72 if(rs == "complete") {
77 // no matter what, make sure it fires on load
78 E.on(window, "load", fireDocReady);
81 var createBuffered = function(h, o){
82 var task = new Roo.util.DelayedTask(h);
84 // create new event object impl so new events don't wipe out properties
85 e = new Roo.EventObjectImpl(e);
86 task.delay(o.buffer, h, null, [e]);
90 var createSingle = function(h, el, ename, fn){
92 Roo.EventManager.removeListener(el, ename, fn);
97 var createDelayed = function(h, o){
99 // create new event object impl so new events don't wipe out properties
100 e = new Roo.EventObjectImpl(e);
101 setTimeout(function(){
106 var transitionEndVal = false;
108 var transitionEnd = funciton()
110 if (transitionEndVal) {
111 return transitionEndVal;
113 var el = document.createElement('div')
115 var transEndEventNames = {
116 WebkitTransition : 'webkitTransitionEnd',
117 MozTransition : 'transitionend',
118 OTransition : 'oTransitionEnd otransitionend',
119 transition : 'transitionend'
122 for (var name in transEndEventNames) {
123 if (el.style[name] !== undefined) {
124 transitionEndVal = transEndEventNames[name];
125 return transitionEndVal ;
131 var listen = function(element, ename, opt, fn, scope){
132 var o = (!opt || typeof opt == "boolean") ? {} : opt;
133 fn = fn || o.fn; scope = scope || o.scope;
134 var el = Roo.getDom(element);
136 throw "Error listening for \"" + ename + '\". Element "' + element + '" doesn\'t exist.';
139 e = Roo.EventObject.setEvent(e);
142 t = e.getTarget(o.delegate, el);
149 if(o.stopEvent === true){
152 if(o.preventDefault === true){
155 if(o.stopPropagation === true){
159 if(o.normalized === false){
163 fn.call(scope || el, e, t, o);
166 h = createDelayed(h, o);
169 h = createSingle(h, el, ename, fn);
172 h = createBuffered(h, o);
174 fn._handlers = fn._handlers || [];
175 fn._handlers.push([Roo.id(el), ename, h]);
177 if (ename == 'transitionend') {
180 for (var name in transEndEventNames) {
181 if (el.style[name] !== undefined) {
182 return { end: transEndEventNames[name] }
189 if(ename == "mousewheel" && el.addEventListener){ // workaround for jQuery
190 el.addEventListener("DOMMouseScroll", h, false);
191 E.on(window, 'unload', function(){
192 el.removeEventListener("DOMMouseScroll", h, false);
195 if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document
196 Roo.EventManager.stoppedMouseDownEvent.addListener(h);
201 var stopListening = function(el, ename, fn){
202 var id = Roo.id(el), hds = fn._handlers, hd = fn;
204 for(var i = 0, len = hds.length; i < len; i++){
206 if(h[0] == id && h[1] == ename){
215 if(ename == "mousewheel" && el.addEventListener){
216 el.removeEventListener("DOMMouseScroll", hd, false);
218 if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document
219 Roo.EventManager.stoppedMouseDownEvent.removeListener(hd);
223 var propRe = /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/;
230 * @scope Roo.EventManager
235 * This is no longer needed and is deprecated. Places a simple wrapper around an event handler to override the browser event
236 * object with a Roo.EventObject
237 * @param {Function} fn The method the event invokes
238 * @param {Object} scope An object that becomes the scope of the handler
239 * @param {boolean} override If true, the obj passed in becomes
240 * the execution scope of the listener
241 * @return {Function} The wrapped function
244 wrap : function(fn, scope, override){
246 Roo.EventObject.setEvent(e);
247 fn.call(override ? scope || window : window, Roo.EventObject, scope);
252 * Appends an event handler to an element (shorthand for addListener)
253 * @param {String/HTMLElement} element The html element or id to assign the
254 * @param {String} eventName The type of event to listen for
255 * @param {Function} handler The method the event invokes
256 * @param {Object} scope (optional) The scope in which to execute the handler
257 * function. The handler function's "this" context.
258 * @param {Object} options (optional) An object containing handler configuration
259 * properties. This may contain any of the following properties:<ul>
260 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
261 * <li>delegate {String} A simple selector to filter the target or look for a descendant of the target</li>
262 * <li>stopEvent {Boolean} True to stop the event. That is stop propagation, and prevent the default action.</li>
263 * <li>preventDefault {Boolean} True to prevent the default action</li>
264 * <li>stopPropagation {Boolean} True to prevent event propagation</li>
265 * <li>normalized {Boolean} False to pass a browser event to the handler function instead of an Roo.EventObject</li>
266 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
267 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
268 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
269 * by the specified number of milliseconds. If the event fires again within that time, the original
270 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
273 * <b>Combining Options</b><br>
274 * Using the options argument, it is possible to combine different types of listeners:<br>
276 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)<div style="margin: 5px 20px 20px;">
278 el.on('click', this.onClick, this, {
285 * <b>Attaching multiple handlers in 1 call</b><br>
286 * The method also allows for a single argument to be passed which is a config object containing properties
287 * which specify multiple handlers.
306 * Or a shorthand syntax:<br>
309 'click' : this.onClick,
310 'mouseover' : this.onMouseOver,
311 'mouseout' : this.onMouseOut
315 addListener : function(element, eventName, fn, scope, options){
316 if(typeof eventName == "object"){
322 if(typeof o[e] == "function"){
324 listen(element, e, o, o[e], o.scope);
326 // individual options
327 listen(element, e, o[e]);
332 return listen(element, eventName, options, fn, scope);
336 * Removes an event handler
338 * @param {String/HTMLElement} element The id or html element to remove the
340 * @param {String} eventName The type of event
341 * @param {Function} fn
342 * @return {Boolean} True if a listener was actually removed
344 removeListener : function(element, eventName, fn){
345 return stopListening(element, eventName, fn);
349 * Fires when the document is ready (before onload and before images are loaded). Can be
350 * accessed shorthanded Roo.onReady().
351 * @param {Function} fn The method the event invokes
352 * @param {Object} scope An object that becomes the scope of the handler
353 * @param {boolean} options
355 onDocumentReady : function(fn, scope, options){
356 if(docReadyState){ // if it already fired
357 docReadyEvent.addListener(fn, scope, options);
358 docReadyEvent.fire();
359 docReadyEvent.clearListeners();
365 docReadyEvent.addListener(fn, scope, options);
369 * Fires when the window is resized and provides resize event buffering (50 milliseconds), passes new viewport width and height to handlers.
370 * @param {Function} fn The method the event invokes
371 * @param {Object} scope An object that becomes the scope of the handler
372 * @param {boolean} options
374 onWindowResize : function(fn, scope, options){
376 resizeEvent = new Roo.util.Event();
377 resizeTask = new Roo.util.DelayedTask(function(){
378 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
380 E.on(window, "resize", function(){
382 resizeTask.delay(50);
384 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
388 resizeEvent.addListener(fn, scope, options);
392 * Fires when the user changes the active text size. Handler gets called with 2 params, the old size and the new size.
393 * @param {Function} fn The method the event invokes
394 * @param {Object} scope An object that becomes the scope of the handler
395 * @param {boolean} options
397 onTextResize : function(fn, scope, options){
399 textEvent = new Roo.util.Event();
400 var textEl = new Roo.Element(document.createElement('div'));
401 textEl.dom.className = 'x-text-resize';
402 textEl.dom.innerHTML = 'X';
403 textEl.appendTo(document.body);
404 textSize = textEl.dom.offsetHeight;
405 setInterval(function(){
406 if(textEl.dom.offsetHeight != textSize){
407 textEvent.fire(textSize, textSize = textEl.dom.offsetHeight);
409 }, this.textResizeInterval);
411 textEvent.addListener(fn, scope, options);
415 * Removes the passed window resize listener.
416 * @param {Function} fn The method the event invokes
417 * @param {Object} scope The scope of handler
419 removeResizeListener : function(fn, scope){
421 resizeEvent.removeListener(fn, scope);
426 fireResize : function(){
428 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
432 * Url used for onDocumentReady with using SSL (defaults to Roo.SSL_SECURE_URL)
436 * The frequency, in milliseconds, to check for text resize events (defaults to 50)
438 textResizeInterval : 50
443 * @scopeAlias pub=Roo.EventManager
447 * Appends an event handler to an element (shorthand for addListener)
448 * @param {String/HTMLElement} element The html element or id to assign the
449 * @param {String} eventName The type of event to listen for
450 * @param {Function} handler The method the event invokes
451 * @param {Object} scope (optional) The scope in which to execute the handler
452 * function. The handler function's "this" context.
453 * @param {Object} options (optional) An object containing handler configuration
454 * properties. This may contain any of the following properties:<ul>
455 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
456 * <li>delegate {String} A simple selector to filter the target or look for a descendant of the target</li>
457 * <li>stopEvent {Boolean} True to stop the event. That is stop propagation, and prevent the default action.</li>
458 * <li>preventDefault {Boolean} True to prevent the default action</li>
459 * <li>stopPropagation {Boolean} True to prevent event propagation</li>
460 * <li>normalized {Boolean} False to pass a browser event to the handler function instead of an Roo.EventObject</li>
461 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
462 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
463 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
464 * by the specified number of milliseconds. If the event fires again within that time, the original
465 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
468 * <b>Combining Options</b><br>
469 * Using the options argument, it is possible to combine different types of listeners:<br>
471 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)<div style="margin: 5px 20px 20px;">
473 el.on('click', this.onClick, this, {
480 * <b>Attaching multiple handlers in 1 call</b><br>
481 * The method also allows for a single argument to be passed which is a config object containing properties
482 * which specify multiple handlers.
501 * Or a shorthand syntax:<br>
504 'click' : this.onClick,
505 'mouseover' : this.onMouseOver,
506 'mouseout' : this.onMouseOut
510 pub.on = pub.addListener;
511 pub.un = pub.removeListener;
513 pub.stoppedMouseDownEvent = new Roo.util.Event();
517 * Fires when the document is ready (before onload and before images are loaded). Shorthand of {@link Roo.EventManager#onDocumentReady}.
518 * @param {Function} fn The method the event invokes
519 * @param {Object} scope An object that becomes the scope of the handler
520 * @param {boolean} override If true, the obj passed in becomes
521 * the execution scope of the listener
525 Roo.onReady = Roo.EventManager.onDocumentReady;
527 Roo.onReady(function(){
528 var bd = Roo.get(document.body);
533 : Roo.isGecko ? "roo-gecko"
534 : Roo.isOpera ? "roo-opera"
535 : Roo.isSafari ? "roo-safari" : ""];
541 cls.push("roo-linux");
544 cls.push('roo-border-box');
546 if(Roo.isStrict){ // add to the parent to allow for selectors like ".ext-strict .ext-ie"
547 var p = bd.dom.parentNode;
549 p.className += ' roo-strict';
552 bd.addClass(cls.join(' '));
556 * @class Roo.EventObject
557 * EventObject exposes the Yahoo! UI Event functionality directly on the object
558 * passed to your event handler. It exists mostly for convenience. It also fixes the annoying null checks automatically to cleanup your code
561 function handleClick(e){ // e is not a standard event object, it is a Roo.EventObject
563 var target = e.getTarget();
566 var myDiv = Roo.get("myDiv");
567 myDiv.on("click", handleClick);
569 Roo.EventManager.on("myDiv", 'click', handleClick);
570 Roo.EventManager.addListener("myDiv", 'click', handleClick);
574 Roo.EventObject = function(){
576 var E = Roo.lib.Event;
578 // safari keypress events for special keys return bad keycodes
584 63276 : 33, // page up
585 63277 : 34, // page down
586 63272 : 46, // delete
591 // normalize button clicks
592 var btnMap = Roo.isIE ? {1:0,4:1,2:2} :
593 (Roo.isSafari ? {1:0,2:1,3:2} : {0:0,1:1,2:2});
595 Roo.EventObjectImpl = function(e){
597 this.setEvent(e.browserEvent || e);
600 Roo.EventObjectImpl.prototype = {
602 * Used to fix doc tools.
603 * @scope Roo.EventObject.prototype
609 /** The normal browser event */
611 /** The button pressed in a mouse event */
613 /** True if the shift key was down during the event */
615 /** True if the control key was down during the event */
617 /** True if the alt key was down during the event */
676 setEvent : function(e){
677 if(e == this || (e && e.browserEvent)){ // already wrapped
680 this.browserEvent = e;
683 this.button = e.button ? btnMap[e.button] : (e.which ? e.which-1 : -1);
684 if(e.type == 'click' && this.button == -1){
688 this.shiftKey = e.shiftKey;
689 // mac metaKey behaves like ctrlKey
690 this.ctrlKey = e.ctrlKey || e.metaKey;
691 this.altKey = e.altKey;
692 // in getKey these will be normalized for the mac
693 this.keyCode = e.keyCode;
694 // keyup warnings on firefox.
695 this.charCode = (e.type == 'keyup' || e.type == 'keydown') ? 0 : e.charCode;
696 // cache the target for the delayed and or buffered events
697 this.target = E.getTarget(e);
699 this.xy = E.getXY(e);
702 this.shiftKey = false;
703 this.ctrlKey = false;
714 * Stop the event (preventDefault and stopPropagation)
716 stopEvent : function(){
717 if(this.browserEvent){
718 if(this.browserEvent.type == 'mousedown'){
719 Roo.EventManager.stoppedMouseDownEvent.fire(this);
721 E.stopEvent(this.browserEvent);
726 * Prevents the browsers default handling of the event.
728 preventDefault : function(){
729 if(this.browserEvent){
730 E.preventDefault(this.browserEvent);
735 isNavKeyPress : function(){
736 var k = this.keyCode;
737 k = Roo.isSafari ? (safariKeys[k] || k) : k;
738 return (k >= 33 && k <= 40) || k == this.RETURN || k == this.TAB || k == this.ESC;
741 isSpecialKey : function(){
742 var k = this.keyCode;
743 return (this.type == 'keypress' && this.ctrlKey) || k == 9 || k == 13 || k == 40 || k == 27 ||
744 (k == 16) || (k == 17) ||
745 (k >= 18 && k <= 20) ||
746 (k >= 33 && k <= 35) ||
747 (k >= 36 && k <= 39) ||
748 (k >= 44 && k <= 45);
751 * Cancels bubbling of the event.
753 stopPropagation : function(){
754 if(this.browserEvent){
755 if(this.type == 'mousedown'){
756 Roo.EventManager.stoppedMouseDownEvent.fire(this);
758 E.stopPropagation(this.browserEvent);
763 * Gets the key code for the event.
766 getCharCode : function(){
767 return this.charCode || this.keyCode;
771 * Returns a normalized keyCode for the event.
772 * @return {Number} The key code
775 var k = this.keyCode || this.charCode;
776 return Roo.isSafari ? (safariKeys[k] || k) : k;
780 * Gets the x coordinate of the event.
783 getPageX : function(){
788 * Gets the y coordinate of the event.
791 getPageY : function(){
796 * Gets the time of the event.
799 getTime : function(){
800 if(this.browserEvent){
801 return E.getTime(this.browserEvent);
807 * Gets the page coordinates of the event.
808 * @return {Array} The xy values like [x, y]
815 * Gets the target for the event.
816 * @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target
817 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
818 search as a number or element (defaults to 10 || document.body)
819 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
820 * @return {HTMLelement}
822 getTarget : function(selector, maxDepth, returnEl){
823 return selector ? Roo.fly(this.target).findParent(selector, maxDepth, returnEl) : this.target;
826 * Gets the related target.
827 * @return {HTMLElement}
829 getRelatedTarget : function(){
830 if(this.browserEvent){
831 return E.getRelatedTarget(this.browserEvent);
837 * Normalizes mouse wheel delta across browsers
838 * @return {Number} The delta
840 getWheelDelta : function(){
841 var e = this.browserEvent;
843 if(e.wheelDelta){ /* IE/Opera. */
844 delta = e.wheelDelta/120;
845 }else if(e.detail){ /* Mozilla case. */
852 * Returns true if the control, meta, shift or alt key was pressed during this event.
855 hasModifier : function(){
856 return !!((this.ctrlKey || this.altKey) || this.shiftKey);
860 * Returns true if the target of this event equals el or is a child of el
861 * @param {String/HTMLElement/Element} el
862 * @param {Boolean} related (optional) true to test if the related target is within el instead of the target
865 within : function(el, related){
866 var t = this[related ? "getRelatedTarget" : "getTarget"]();
867 return t && Roo.fly(el).contains(t);
870 getPoint : function(){
871 return new Roo.lib.Point(this.xy[0], this.xy[1]);
875 return new Roo.EventObjectImpl();