2 Copyright (c) 2010, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.com/yui/license.html
8 var GLOBAL_ENV = YUI.Env;
10 if (!GLOBAL_ENV._ready) {
11 GLOBAL_ENV._ready = function() {
12 GLOBAL_ENV.DOMReady = true;
13 GLOBAL_ENV.remove(YUI.config.doc, 'DOMContentLoaded', GLOBAL_ENV._ready);
17 GLOBAL_ENV.add(YUI.config.doc, 'DOMContentLoaded', GLOBAL_ENV._ready);
21 YUI.add('event-base', function(Y) {
24 * DOM event listener abstraction layer
26 * @submodule event-base
30 * The domready event fires at the moment the browser's DOM is
31 * usable. In most cases, this is before images are fully
32 * downloaded, allowing you to provide a more responsive user
35 * In YUI 3, domready subscribers will be notified immediately if
36 * that moment has already passed when the subscription is created.
38 * One exception is if the yui.js file is dynamically injected into
39 * the page. If this is done, you must tell the YUI instance that
40 * you did this in order for DOMReady (and window load events) to
41 * fire normally. That configuration option is 'injected' -- set
42 * it to true if the yui.js script is not included inline.
44 * This method is part of the 'event-ready' module, which is a
45 * submodule of 'event'.
50 Y.publish('domready', {
55 if (GLOBAL_ENV.DOMReady) {
58 Y.Do.before(function() { Y.fire('domready'); }, YUI.Env, '_ready');
62 * Custom event engine, DOM event listener abstraction layer, synthetic DOM
65 * @submodule event-base
69 * Wraps a DOM event, properties requiring browser abstraction are
70 * fixed here. Provids a security layer when required.
71 * @class DOMEventFacade
72 * @param ev {Event} the DOM event
73 * @param currentTarget {HTMLElement} the element the listener was attached to
74 * @param wrapper {Event.Custom} the custom event wrapper for this DOM event
82 * webkit key remapping required for Safari < 3.1
83 * @property webkitKeymap
92 63277: 34, // page down
93 25: 9, // SHIFT-TAB (Safari provides a different key code in
94 // this case, even though the shiftKey modifier is set)
101 * Returns a wrapped node. Intended to be used on event targets,
102 * so it will return the node's parent if the target is a text
105 * If accessing a property of the node throws an error, this is
106 * probably the anonymous div wrapper Gecko adds inside text
107 * nodes. This likely will only occur when attempting to access
108 * the relatedTarget. In this case, we now return null because
109 * the anonymous div is completely useless and we do not know
110 * what the related target was because we can't even get to
111 * the element's parent node.
116 resolve = function(n) {
121 if (n && 3 == n.nodeType) {
131 DOMEventFacade = function(ev, currentTarget, wrapper) {
133 this._currentTarget = currentTarget;
134 this._wrapper = wrapper || EMPTY;
140 Y.extend(DOMEventFacade, Object, {
145 overrides = this._wrapper.overrides,
149 currentTarget = this._currentTarget;
151 this.altKey = e.altKey;
152 this.ctrlKey = e.ctrlKey;
153 this.metaKey = e.metaKey;
154 this.shiftKey = e.shiftKey;
155 this.type = (overrides && overrides.type) || e.type;
156 this.clientX = e.clientX;
157 this.clientY = e.clientY;
162 c = e.keyCode || e.charCode;
164 if (ua.webkit && (c in webkitKeymap)) {
170 this.which = e.which || e.charCode || c;
171 // this.button = e.button;
172 this.button = this.which;
174 this.target = resolve(e.target);
175 this.currentTarget = resolve(currentTarget);
176 this.relatedTarget = resolve(e.relatedTarget);
178 if (e.type == "mousewheel" || e.type == "DOMMouseScroll") {
179 this.wheelDelta = (e.detail) ? (e.detail * -1) : Math.round(e.wheelDelta / 80) || ((e.wheelDelta < 0) ? -1 : 1);
183 this._touch(e, currentTarget, this._wrapper);
187 stopPropagation: function() {
188 this._event.stopPropagation();
189 this._wrapper.stopped = 1;
193 stopImmediatePropagation: function() {
195 if (e.stopImmediatePropagation) {
196 e.stopImmediatePropagation();
198 this.stopPropagation();
200 this._wrapper.stopped = 2;
204 preventDefault: function(returnValue) {
207 e.returnValue = returnValue || false;
208 this._wrapper.prevented = 1;
212 halt: function(immediate) {
214 this.stopImmediatePropagation();
216 this.stopPropagation();
219 this.preventDefault();
224 DOMEventFacade.resolve = resolve;
225 Y.DOM2EventFacade = DOMEventFacade;
226 Y.DOMEventFacade = DOMEventFacade;
234 * The X location of the event on the page (including scroll)
240 * The Y location of the event on the page (including scroll)
246 * The keyCode for key events. Uses charCode if keyCode is not available
252 * The charCode for key events. Same as keyCode
258 * The button that was pushed.
264 * The button that was pushed. Same as button.
270 * Node reference for the targeted element
276 * Node reference for the element that the listener was attached to.
277 * @propery currentTarget
282 * Node reference to the relatedTarget
283 * @propery relatedTarget
288 * Number representing the direction and velocity of the movement of the mousewheel.
289 * Negative is down, the higher the number, the faster. Applies to the mousewheel event.
290 * @property wheelDelta
295 * Stops the propagation to the next bubble target
296 * @method stopPropagation
300 * Stops the propagation to the next bubble target and
301 * prevents any additional listeners from being exectued
302 * on the current target.
303 * @method stopImmediatePropagation
307 * Prevents the event's default behavior
308 * @method preventDefault
309 * @param returnValue {string} sets the returnValue of the event to this value
310 * (rather than the default false value). This can be used to add a customized
311 * confirmation query to the beforeunload event).
315 * Stops the event propagation and prevents the default
318 * @param immediate {boolean} if true additional listeners
319 * on the current target will not be executed
323 * DOM event listener abstraction layer
325 * @submodule event-base
329 * The event utility provides functions to add and remove event listeners,
330 * event cleansing. It also tries to automatically remove listeners it
331 * registers during the unload event.
337 Y.Env.evt.dom_wrappers = {};
338 Y.Env.evt.dom_map = {};
340 var _eventenv = Y.Env.evt,
344 remove = YUI.Env.remove,
346 onLoad = function() {
347 YUI.Env.windowLoaded = true;
349 remove(win, "load", onLoad);
352 onUnload = function() {
356 EVENT_READY = 'domready',
358 COMPAT_ARG = '~yui|2|compat~',
360 shouldIterate = function(o) {
362 return (o && typeof o !== "string" && Y.Lang.isNumber(o.length) &&
363 !o.tagName && !o.alert);
373 * True after the onload event has fired
374 * @property _loadComplete
379 var _loadComplete = false,
382 * The number of times to poll after window.onload. This number is
383 * increased if additional late-bound handlers are requested after
385 * @property _retryCount
392 * onAvailable listeners
400 * Custom event wrappers for DOM events. Key is
401 * 'event:' + Element uid stamp + event type
402 * @property _wrappers
403 * @type Y.Event.Custom
407 _wrappers = _eventenv.dom_wrappers,
409 _windowLoadKey = null,
412 * Custom event wrapper map DOM events. Key is
413 * Element uid stamp. Each item is a hash of custom event
414 * wrappers as provided in the _wrappers collection. This
415 * provides the infrastructure for getListeners.
416 * @property _el_events
420 _el_events = _eventenv.dom_map;
425 * The number of times we should look for elements that are not
426 * in the DOM at the time the event is requested after the document
427 * has been loaded. The default is 1000@amp;40 ms, so it will poll
428 * for 40 seconds or until all outstanding handlers are bound
429 * (whichever comes first).
430 * @property POLL_RETRYS
438 * The poll interval in milliseconds
439 * @property POLL_INTERVAL
447 * addListener/removeListener can throw errors in unexpected scenarios.
448 * These errors are suppressed, the method returns false, and this property
450 * @property lastError
459 * @property _interval
466 * document readystate poll handle
474 * True when the document is initially usable
482 * @method startInterval
486 startInterval: function() {
487 if (!Event._interval) {
488 Event._interval = setInterval(Event._poll, Event.POLL_INTERVAL);
493 * Executes the supplied callback when the item with the supplied
494 * id is found. This is meant to be used to execute behavior as
495 * soon as possible as the page loads. If you use this after the
496 * initial page load it will poll for a fixed time for the element.
497 * The number of times it will poll and the frequency are
498 * configurable. By default it will poll for 10 seconds.
500 * <p>The callback is executed with a single parameter:
501 * the custom object parameter, if provided.</p>
503 * @method onAvailable
505 * @param {string||string[]} id the id of the element, or an array
506 * of ids to look for.
507 * @param {function} fn what to execute when the element is found.
508 * @param {object} p_obj an optional object to be passed back as
510 * @param {boolean|object} p_override If set to true, fn will execute
511 * in the context of p_obj, if set to an object it
512 * will execute in the context of that object
513 * @param checkContent {boolean} check child node readiness (onContentReady)
515 * @deprecated Use Y.on("available")
517 // @TODO fix arguments
518 onAvailable: function(id, fn, p_obj, p_override, checkContent, compat) {
520 var a = Y.Array(id), i, availHandle;
523 for (i=0; i<a.length; i=i+1) {
528 override: p_override,
529 checkReady: checkContent,
533 _retryCount = this.POLL_RETRYS;
535 // We want the first test to be immediate, but async
536 setTimeout(Event._poll, 0);
538 availHandle = new Y.EventHandle({
540 _delete: function() {
541 // set by the event system for lazy DOM listeners
542 if (availHandle.handle) {
543 availHandle.handle.detach();
549 // otherwise try to remove the onAvailable listener(s)
550 for (i = 0; i < a.length; i++) {
551 for (j = 0; j < _avail.length; j++) {
552 if (a[i] === _avail[j].id) {
565 * Works the same way as onAvailable, but additionally checks the
566 * state of sibling elements to determine if the content of the
567 * available element is safe to modify.
569 * <p>The callback is executed with a single parameter:
570 * the custom object parameter, if provided.</p>
572 * @method onContentReady
574 * @param {string} id the id of the element to look for.
575 * @param {function} fn what to execute when the element is ready.
576 * @param {object} obj an optional object to be passed back as
578 * @param {boolean|object} override If set to true, fn will execute
579 * in the context of p_obj. If an object, fn will
580 * exectute in the context of that object
583 * @deprecated Use Y.on("contentready")
585 // @TODO fix arguments
586 onContentReady: function(id, fn, obj, override, compat) {
587 return Event.onAvailable(id, fn, obj, override, true, compat);
591 * Adds an event listener
595 * @param {String} type The type of event to append
596 * @param {Function} fn The method the event invokes
597 * @param {String|HTMLElement|Array|NodeList} el An id, an element
598 * reference, or a collection of ids and/or elements to assign the
600 * @param {Object} context optional context object
601 * @param {Boolean|object} args 0..n arguments to pass to the callback
602 * @return {EventHandle} an object to that can be used to detach the listener
607 attach: function(type, fn, el, context) {
608 return Event._attach(Y.Array(arguments, 0, true));
611 _createWrapper: function (el, type, capture, compat, facade) {
615 key = 'event:' + ek + type;
617 if (false === facade) {
625 cewrapper = _wrappers[key];
630 cewrapper = Y.publish(key, {
633 contextFn: function() {
637 cewrapper.nodeRef = cewrapper.nodeRef || Y.one(cewrapper.el);
638 return cewrapper.nodeRef;
643 cewrapper.overrides = {};
645 // for later removeListener calls
648 cewrapper.domkey = ek;
649 cewrapper.type = type;
650 cewrapper.fn = function(e) {
651 cewrapper.fire(Event.getEvent(e, el, (compat || (false === facade))));
653 cewrapper.capture = capture;
655 if (el == win && type == "load") {
656 // window load happens once
657 cewrapper.fireOnce = true;
658 _windowLoadKey = key;
661 _wrappers[key] = cewrapper;
662 _el_events[ek] = _el_events[ek] || {};
663 _el_events[ek][key] = cewrapper;
665 add(el, type, cewrapper.fn, capture);
672 _attach: function(args, conf) {
675 handles, oEl, cewrapper, context,
676 fireNow = false, ret,
680 facade = conf && conf.facade,
681 capture = conf && conf.capture,
682 overrides = conf && conf.overrides;
684 if (args[args.length-1] === COMPAT_ARG) {
686 // trimmedArgs.pop();
689 if (!fn || !fn.call) {
690 // throw new TypeError(type + " attach call failed, callback undefined");
694 // The el argument can be an array of elements or element ids.
695 if (shouldIterate(el)) {
699 Y.each(el, function(v, k) {
701 handles.push(Event._attach(args, conf));
704 // return (handles.length === 1) ? handles[0] : handles;
705 return new Y.EventHandle(handles);
707 // If the el argument is a string, we assume it is
708 // actually the id of the element. If the page is loaded
709 // we convert el to the actual element, otherwise we
710 // defer attaching the event until the element is
712 } else if (Y.Lang.isString(el)) {
714 // oEl = (compat) ? Y.DOM.byId(el) : Y.Selector.query(el);
717 oEl = Y.DOM.byId(el);
720 oEl = Y.Selector.query(el);
722 switch (oEl.length) {
731 return Event._attach(args, conf);
739 // Not found = defer adding the event until the element is available
742 ret = Event.onAvailable(el, function() {
744 ret.handle = Event._attach(args, conf);
746 }, Event, true, false, compat);
753 // Element should be an html element or node
758 if (Y.Node && Y.instanceOf(el, Y.Node)) {
759 el = Y.Node.getDOMNode(el);
762 cewrapper = Event._createWrapper(el, type, capture, compat, facade);
764 Y.mix(cewrapper.overrides, overrides);
767 if (el == win && type == "load") {
769 // if the load is complete, fire immediately.
770 // all subscribers, including the current one
772 if (YUI.Env.windowLoaded) {
783 // set context to the Node if not specified
784 // ret = cewrapper.on.apply(cewrapper, trimmedArgs);
785 ret = cewrapper._on(fn, context, (args.length > 4) ? args.slice(4) : null);
796 * Removes an event listener. Supports the signature the event was bound
797 * with, but the preferred way to remove listeners is using the handle
798 * that is returned when using Y.on
802 * @param {String} type the type of event to remove.
803 * @param {Function} fn the method the event invokes. If fn is
804 * undefined, then all event handlers for the type of event are
806 * @param {String|HTMLElement|Array|NodeList|EventHandle} el An
807 * event handle, an id, an element reference, or a collection
808 * of ids and/or elements to remove the listener from.
809 * @return {boolean} true if the unbind was successful, false otherwise.
812 detach: function(type, fn, el, obj) {
814 var args=Y.Array(arguments, 0, true), compat, l, ok, i,
817 if (args[args.length-1] === COMPAT_ARG) {
822 if (type && type.detach) {
823 return type.detach();
826 // The el argument can be a string
827 if (typeof el == "string") {
829 // el = (compat) ? Y.DOM.byId(el) : Y.all(el);
833 el = Y.Selector.query(el);
841 // return Event.detach.apply(Event, args);
850 return el.detach.apply(el, args);
851 // The el argument can be an array of elements or element ids.
852 } else if (shouldIterate(el)) {
854 for (i=0, l=el.length; i<l; ++i) {
856 ok = ( Y.Event.detach.apply(Y.Event, args) && ok );
862 if (!type || !fn || !fn.call) {
863 return Event.purgeElement(el, false, type);
866 id = 'event:' + Y.stamp(el) + type;
870 return ce.detach(fn);
878 * Finds the event in the window object, the caller's arguments, or
879 * in the arguments of another method in the callstack. This is
880 * executed automatically for events registered through the event
881 * manager, so the implementer should not normally need to execute
882 * this function at all.
884 * @param {Event} e the event parameter from the handler
885 * @param {HTMLElement} el the element the listener was attached to
886 * @return {Event} the event
889 getEvent: function(e, el, noFacade) {
890 var ev = e || win.event;
892 return (noFacade) ? ev :
893 new Y.DOMEventFacade(ev, el, _wrappers['event:' + Y.stamp(el) + e.type]);
897 * Generates an unique ID for the element if it does not already
900 * @param el the element to create the id for
901 * @return {string} the resulting id of the element
904 generateId: function(el) {
905 return Y.DOM.generateID(el);
909 * We want to be able to use getElementsByTagName as a collection
910 * to attach a group of events to. Unfortunately, different
911 * browsers return different types of collections. This function
912 * tests to determine if the object is array-like. It will also
913 * fail if the object is an array, but is empty.
914 * @method _isValidCollection
915 * @param o the object to test
916 * @return {boolean} true if the object is array-like and populated
917 * @deprecated was not meant to be used directly
921 _isValidCollection: shouldIterate,
924 * hook up any deferred listeners
930 if (!_loadComplete) {
931 _loadComplete = true;
933 // Just in case DOMReady did not go off for some reason
939 // Available elements may not have been detected before the
940 // window load event fires. Try to find them now so that the
941 // the user is more likely to get the onAvailable notifications
942 // before the window load notification
948 * Polling function that runs before the onload event fires,
949 * attempting to attach to DOM Nodes as soon as they are
960 if (Y.UA.ie && !YUI.Env.DOMReady) {
961 // Hold off if DOMReady has not fired and check current
962 // readyState to protect against the IE operation aborted
964 Event.startInterval();
970 // keep trying until after the page is loaded. We need to
971 // check the page load state prior to trying to bind the
972 // elements so that we can be certain all elements have been
973 // tested appropriately
974 var i, len, item, el, notAvail, executeItem,
975 tryAgain = !_loadComplete;
978 tryAgain = (_retryCount > 0);
984 executeItem = function (el, item) {
985 var context, ov = item.override;
996 item.fn.call(context, item.obj);
998 context = item.obj || Y.one(el);
999 item.fn.apply(context, (Y.Lang.isArray(ov)) ? ov : []);
1004 for (i=0,len=_avail.length; i<len; ++i) {
1006 if (item && !item.checkReady) {
1008 // el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id);
1009 el = (item.compat) ? Y.DOM.byId(item.id) : Y.Selector.query(item.id, null, true);
1012 executeItem(el, item);
1015 notAvail.push(item);
1021 for (i=0,len=_avail.length; i<len; ++i) {
1023 if (item && item.checkReady) {
1025 // el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id);
1026 el = (item.compat) ? Y.DOM.byId(item.id) : Y.Selector.query(item.id, null, true);
1029 // The element is available, but not necessarily ready
1030 // @todo should we test parentNode.nextSibling?
1031 if (_loadComplete || (el.get && el.get('nextSibling')) || el.nextSibling) {
1032 executeItem(el, item);
1036 notAvail.push(item);
1041 _retryCount = (notAvail.length === 0) ? 0 : _retryCount - 1;
1044 // we may need to strip the nulled out items here
1045 Event.startInterval();
1047 clearInterval(Event._interval);
1048 Event._interval = null;
1051 Event.locked = false;
1058 * Removes all listeners attached to the given element via addListener.
1059 * Optionally, the node's children can also be purged.
1060 * Optionally, you can specify a specific type of event to remove.
1061 * @method purgeElement
1062 * @param {HTMLElement} el the element to purge
1063 * @param {boolean} recurse recursively purge this element's children
1064 * as well. Use with caution.
1065 * @param {string} type optional type of listener to purge. If
1066 * left out, all listeners will be removed
1069 purgeElement: function(el, recurse, type) {
1070 // var oEl = (Y.Lang.isString(el)) ? Y.one(el) : el,
1071 var oEl = (Y.Lang.isString(el)) ? Y.Selector.query(el, null, true) : el,
1072 lis = Event.getListeners(oEl, type), i, len, props, children, child;
1074 if (recurse && oEl) {
1076 children = Y.Selector.query('*', oEl);
1078 len = children.length;
1079 for (; i < len; ++i) {
1080 child = Event.getListeners(children[i], type);
1082 lis = lis.concat(child);
1090 for (; i < len; ++i) {
1093 remove(props.el, props.type, props.fn, props.capture);
1094 delete _wrappers[props.key];
1095 delete _el_events[props.domkey][props.key];
1103 * Returns all listeners attached to the given element via addListener.
1104 * Optionally, you can specify a specific type of event to return.
1105 * @method getListeners
1106 * @param el {HTMLElement|string} the element or element id to inspect
1107 * @param type {string} optional type of listener to return. If
1108 * left out, all listeners will be returned
1109 * @return {Y.Custom.Event} the custom event wrapper for the DOM event(s)
1112 getListeners: function(el, type) {
1113 var ek = Y.stamp(el, true), evts = _el_events[ek],
1114 results=[] , key = (type) ? 'event:' + ek + type : null,
1115 adapters = _eventenv.plugins;
1122 // look for synthetic events
1123 if (adapters[type] && adapters[type].eventDef) {
1128 results.push(evts[key]);
1131 // get native events as well
1134 results.push(evts[key]);
1138 Y.each(evts, function(v, k) {
1143 return (results.length) ? results : null;
1147 * Removes all listeners registered by pe.event. Called
1148 * automatically during the unload event.
1153 _unload: function(e) {
1154 Y.each(_wrappers, function(v, k) {
1156 remove(v.el, v.type, v.fn, v.capture);
1157 delete _wrappers[k];
1158 delete _el_events[v.domkey][k];
1160 remove(win, "unload", onUnload);
1164 * Adds a DOM event directly without the caching, cleanup, context adj, etc
1167 * @param {HTMLElement} el the element to bind the handler to
1168 * @param {string} type the type of event handler
1169 * @param {function} fn the callback to invoke
1170 * @param {boolen} capture capture or bubble phase
1177 * Basic remove listener
1179 * @method nativeRemove
1180 * @param {HTMLElement} el the element to bind the handler to
1181 * @param {string} type the type of event handler
1182 * @param {function} fn the callback to invoke
1183 * @param {boolen} capture capture or bubble phase
1187 nativeRemove: remove
1194 if (config.injected || YUI.Env.windowLoaded) {
1197 add(win, "load", onLoad);
1200 // Process onAvailable/onContentReady items when when the DOM is ready in IE
1202 Y.on(EVENT_READY, Event._poll);
1205 add(win, "unload", onUnload);
1207 Event.Custom = Y.CustomEvent;
1208 Event.Subscriber = Y.Subscriber;
1209 Event.Target = Y.EventTarget;
1210 Event.Handle = Y.EventHandle;
1211 Event.Facade = Y.EventFacade;
1218 * DOM event listener abstraction layer
1220 * @submodule event-base
1224 * Executes the callback as soon as the specified element
1225 * is detected in the DOM. This function expects a selector
1226 * string for the element(s) to detect. If you already have
1227 * an element reference, you don't need this event.
1229 * @param type {string} 'available'
1230 * @param fn {function} the callback function to execute.
1231 * @param el {string} an selector for the element(s) to attach
1232 * @param context optional argument that specifies what 'this' refers to.
1233 * @param args* 0..n additional arguments to pass on to the callback function.
1234 * These arguments will be added after the event object.
1235 * @return {EventHandle} the detach handle
1238 Y.Env.evt.plugins.available = {
1239 on: function(type, fn, id, o) {
1240 var a = arguments.length > 4 ? Y.Array(arguments, 4, true) : null;
1241 return Y.Event.onAvailable.call(Y.Event, id, fn, o, a);
1246 * Executes the callback as soon as the specified element
1247 * is detected in the DOM with a nextSibling property
1248 * (indicating that the element's children are available).
1249 * This function expects a selector
1250 * string for the element(s) to detect. If you already have
1251 * an element reference, you don't need this event.
1252 * @event contentready
1253 * @param type {string} 'contentready'
1254 * @param fn {function} the callback function to execute.
1255 * @param el {string} an selector for the element(s) to attach.
1256 * @param context optional argument that specifies what 'this' refers to.
1257 * @param args* 0..n additional arguments to pass on to the callback function.
1258 * These arguments will be added after the event object.
1259 * @return {EventHandle} the detach handle
1262 Y.Env.evt.plugins.contentready = {
1263 on: function(type, fn, id, o) {
1264 var a = arguments.length > 4 ? Y.Array(arguments, 4, true) : null;
1265 return Y.Event.onContentReady.call(Y.Event, id, fn, o, a);
1270 }, '3.3.0' ,{requires:['event-custom-base']});