2 Copyright (c) 2008, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.net/yui/license.txt
8 * The dom module provides helper methods for manipulating Dom elements.
14 var Y = YAHOO.util, // internal shorthand
16 getStyle, // for load time browser branching
18 propertyCache = {}, // for faster hyphen converts
19 reClassNameCache = {}, // cache regexes for className
20 document = window.document; // cache for faster lookups
22 YAHOO.env._id_counter = YAHOO.env._id_counter || 0; // for use with generateId (global to save state if Dom is overwritten)
25 var isOpera = YAHOO.env.ua.opera,
26 isSafari = YAHOO.env.ua.webkit,
27 isGecko = YAHOO.env.ua.gecko,
28 isIE = YAHOO.env.ua.ie;
32 HYPHEN: /(-[a-z])/i, // to normalize get/setStyle
33 ROOT_TAG: /^body|html$/i, // body for quirks mode, html for standards,
34 OP_SCROLL:/^(?:inline|table-row)$/i
37 var toCamel = function(property) {
38 if ( !patterns.HYPHEN.test(property) ) {
39 return property; // no hyphens
42 if (propertyCache[property]) { // already converted
43 return propertyCache[property];
46 var converted = property;
48 while( patterns.HYPHEN.exec(converted) ) {
49 converted = converted.replace(RegExp.$1,
50 RegExp.$1.substr(1).toUpperCase());
53 propertyCache[property] = converted;
55 //return property.replace(/-([a-z])/gi, function(m0, m1) {return m1.toUpperCase()}) // cant use function as 2nd arg yet due to safari bug
58 var getClassRegEx = function(className) {
59 var re = reClassNameCache[className];
61 re = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)');
62 reClassNameCache[className] = re;
67 // branching at load instead of runtime
68 if (document.defaultView && document.defaultView.getComputedStyle) { // W3C DOM method
69 getStyle = function(el, property) {
72 if (property == 'float') { // fix reserved word
73 property = 'cssFloat';
76 var computed = el.ownerDocument.defaultView.getComputedStyle(el, '');
77 if (computed) { // test computed before touching for safari
78 value = computed[toCamel(property)];
81 return el.style[property] || value;
83 } else if (document.documentElement.currentStyle && isIE) { // IE method
84 getStyle = function(el, property) {
85 switch( toCamel(property) ) {
86 case 'opacity' :// IE opacity uses filter
88 try { // will error if no DXImageTransform
89 val = el.filters['DXImageTransform.Microsoft.Alpha'].opacity;
92 try { // make sure its in the document
93 val = el.filters('alpha').opacity;
98 case 'float': // fix reserved word
99 property = 'styleFloat'; // fall through
101 // test currentStyle before touching
102 var value = el.currentStyle ? el.currentStyle[property] : null;
103 return ( el.style[property] || value );
106 } else { // default to inline only
107 getStyle = function(el, property) { return el.style[property]; };
111 setStyle = function(el, property, val) {
114 if ( lang.isString(el.style.filter) ) { // in case not appended
115 el.style.filter = 'alpha(opacity=' + val * 100 + ')';
117 if (!el.currentStyle || !el.currentStyle.hasLayout) {
118 el.style.zoom = 1; // when no layout or cant tell
123 property = 'styleFloat';
125 el.style[property] = val;
129 setStyle = function(el, property, val) {
130 if (property == 'float') {
131 property = 'cssFloat';
133 el.style[property] = val;
137 var testElement = function(node, method) {
138 return node && node.nodeType == 1 && ( !method || method(node) );
142 * Provides helper methods for DOM elements.
143 * @namespace YAHOO.util
148 * Returns an HTMLElement reference.
150 * @param {String | HTMLElement |Array} el Accepts a string to use as an ID for getting a DOM reference, an actual DOM reference, or an Array of IDs and/or HTMLElements.
151 * @return {HTMLElement | Array} A DOM reference to an HTML element or an array of HTMLElements.
155 if (el.nodeType || el.item) { // Node, or NodeList
159 if (typeof el === 'string') { // id
160 return document.getElementById(el);
163 if ('length' in el) { // array-like
165 for (var i = 0, len = el.length; i < len; ++i) {
166 c[c.length] = Y.Dom.get(el[i]);
172 return el; // some other object, just pass it back
179 * Normalizes currentStyle and ComputedStyle.
181 * @param {String | HTMLElement |Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements.
182 * @param {String} property The style property whose value is returned.
183 * @return {String | Array} The current value of the style property for the element(s).
185 getStyle: function(el, property) {
186 property = toCamel(property);
188 var f = function(element) {
189 return getStyle(element, property);
192 return Y.Dom.batch(el, f, Y.Dom, true);
196 * Wrapper for setting style properties of HTMLElements. Normalizes "opacity" across modern browsers.
198 * @param {String | HTMLElement | Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements.
199 * @param {String} property The style property to be set.
200 * @param {String} val The value to apply to the given property.
202 setStyle: function(el, property, val) {
203 property = toCamel(property);
205 var f = function(element) {
206 setStyle(element, property, val);
210 Y.Dom.batch(el, f, Y.Dom, true);
214 * Gets the current position of an element based on page coordinates. Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
216 * @param {String | HTMLElement | Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements
217 * @return {Array} The XY position of the element(s)
219 getXY: function(el) {
220 var f = function(el) {
221 // has to be part of document to have pageXY
222 if ( (el.parentNode === null || el.offsetParent === null ||
223 this.getStyle(el, 'display') == 'none') && el != el.ownerDocument.body) {
230 return Y.Dom.batch(el, f, Y.Dom, true);
234 * Gets the current X position of an element based on page coordinates. The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
236 * @param {String | HTMLElement | Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements
237 * @return {Number | Array} The X position of the element(s)
240 var f = function(el) {
241 return Y.Dom.getXY(el)[0];
244 return Y.Dom.batch(el, f, Y.Dom, true);
248 * Gets the current Y position of an element based on page coordinates. Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
250 * @param {String | HTMLElement | Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements
251 * @return {Number | Array} The Y position of the element(s)
254 var f = function(el) {
255 return Y.Dom.getXY(el)[1];
258 return Y.Dom.batch(el, f, Y.Dom, true);
262 * Set the position of an html element in page coordinates, regardless of how the element is positioned.
263 * The element(s) must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
265 * @param {String | HTMLElement | Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements
266 * @param {Array} pos Contains X & Y values for new position (coordinates are page-based)
267 * @param {Boolean} noRetry By default we try and set the position a second time if the first fails
269 setXY: function(el, pos, noRetry) {
270 var f = function(el) {
271 var style_pos = this.getStyle(el, 'position');
272 if (style_pos == 'static') { // default to relative
273 this.setStyle(el, 'position', 'relative');
274 style_pos = 'relative';
277 var pageXY = this.getXY(el);
278 if (pageXY === false) { // has to be part of doc to have pageXY
282 var delta = [ // assuming pixels; if not we will have to retry
283 parseInt( this.getStyle(el, 'left'), 10 ),
284 parseInt( this.getStyle(el, 'top'), 10 )
287 if ( isNaN(delta[0]) ) {// in case of 'auto'
288 delta[0] = (style_pos == 'relative') ? 0 : el.offsetLeft;
290 if ( isNaN(delta[1]) ) { // in case of 'auto'
291 delta[1] = (style_pos == 'relative') ? 0 : el.offsetTop;
294 if (pos[0] !== null) { el.style.left = pos[0] - pageXY[0] + delta[0] + 'px'; }
295 if (pos[1] !== null) { el.style.top = pos[1] - pageXY[1] + delta[1] + 'px'; }
298 var newXY = this.getXY(el);
300 // if retry is true, try one more time if we miss
301 if ( (pos[0] !== null && newXY[0] != pos[0]) ||
302 (pos[1] !== null && newXY[1] != pos[1]) ) {
303 this.setXY(el, pos, true);
309 Y.Dom.batch(el, f, Y.Dom, true);
313 * Set the X position of an html element in page coordinates, regardless of how the element is positioned.
314 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
316 * @param {String | HTMLElement | Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements.
317 * @param {Int} x The value to use as the X coordinate for the element(s).
319 setX: function(el, x) {
320 Y.Dom.setXY(el, [x, null]);
324 * Set the Y position of an html element in page coordinates, regardless of how the element is positioned.
325 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
327 * @param {String | HTMLElement | Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements.
328 * @param {Int} x To use as the Y coordinate for the element(s).
330 setY: function(el, y) {
331 Y.Dom.setXY(el, [null, y]);
335 * Returns the region position of the given element.
336 * The element must be part of the DOM tree to have a region (display:none or elements not appended return false).
338 * @param {String | HTMLElement | Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements.
339 * @return {Region | Array} A Region or array of Region instances containing "top, left, bottom, right" member data.
341 getRegion: function(el) {
342 var f = function(el) {
343 if ( (el.parentNode === null || el.offsetParent === null ||
344 this.getStyle(el, 'display') == 'none') && el != el.ownerDocument.body) {
348 var region = Y.Region.getRegion(el);
352 return Y.Dom.batch(el, f, Y.Dom, true);
356 * Returns the width of the client (viewport).
357 * @method getClientWidth
358 * @deprecated Now using getViewportWidth. This interface left intact for back compat.
359 * @return {Int} The width of the viewable area of the page.
361 getClientWidth: function() {
362 return Y.Dom.getViewportWidth();
366 * Returns the height of the client (viewport).
367 * @method getClientHeight
368 * @deprecated Now using getViewportHeight. This interface left intact for back compat.
369 * @return {Int} The height of the viewable area of the page.
371 getClientHeight: function() {
372 return Y.Dom.getViewportHeight();
376 * Returns a array of HTMLElements with the given class.
377 * For optimized performance, include a tag and/or root node when possible.
378 * Note: This method operates against a live collection, so modifying the
379 * collection in the callback (removing/appending nodes, etc.) will have
380 * side effects. Instead you should iterate the returned nodes array,
381 * as you would with the native "getElementsByTagName" method.
382 * @method getElementsByClassName
383 * @param {String} className The class name to match against
384 * @param {String} tag (optional) The tag name of the elements being collected
385 * @param {String | HTMLElement} root (optional) The HTMLElement or an ID to use as the starting point
386 * @param {Function} apply (optional) A function to apply to each element when found
387 * @return {Array} An array of elements that have the given class name
389 getElementsByClassName: function(className, tag, root, apply) {
390 className = lang.trim(className);
392 root = (root) ? Y.Dom.get(root) : null || document;
398 elements = root.getElementsByTagName(tag),
399 re = getClassRegEx(className);
401 for (var i = 0, len = elements.length; i < len; ++i) {
402 if ( re.test(elements[i].className) ) {
403 nodes[nodes.length] = elements[i];
405 apply.call(elements[i], elements[i]);
414 * Determines whether an HTMLElement has the given className.
416 * @param {String | HTMLElement | Array} el The element or collection to test
417 * @param {String} className the class name to search for
418 * @return {Boolean | Array} A boolean value or array of boolean values
420 hasClass: function(el, className) {
421 var re = getClassRegEx(className);
423 var f = function(el) {
424 return re.test(el.className);
427 return Y.Dom.batch(el, f, Y.Dom, true);
431 * Adds a class name to a given element or collection of elements.
433 * @param {String | HTMLElement | Array} el The element or collection to add the class to
434 * @param {String} className the class name to add to the class attribute
435 * @return {Boolean | Array} A pass/fail boolean or array of booleans
437 addClass: function(el, className) {
438 var f = function(el) {
439 if (this.hasClass(el, className)) {
440 return false; // already present
444 el.className = lang.trim([el.className, className].join(' '));
448 return Y.Dom.batch(el, f, Y.Dom, true);
452 * Removes a class name from a given element or collection of elements.
453 * @method removeClass
454 * @param {String | HTMLElement | Array} el The element or collection to remove the class from
455 * @param {String} className the class name to remove from the class attribute
456 * @return {Boolean | Array} A pass/fail boolean or array of booleans
458 removeClass: function(el, className) {
459 var re = getClassRegEx(className);
461 var f = function(el) {
463 current = el.className;
465 if (className && current && this.hasClass(el, className)) {
467 el.className = current.replace(re, ' ');
468 if ( this.hasClass(el, className) ) { // in case of multiple adjacent
469 this.removeClass(el, className);
472 el.className = lang.trim(el.className); // remove any trailing spaces
473 if (el.className === '') { // remove class attribute if empty
474 var attr = (el.hasAttribute) ? 'class' : 'className';
475 el.removeAttribute(attr);
482 return Y.Dom.batch(el, f, Y.Dom, true);
486 * Replace a class with another class for a given element or collection of elements.
487 * If no oldClassName is present, the newClassName is simply added.
488 * @method replaceClass
489 * @param {String | HTMLElement | Array} el The element or collection to remove the class from
490 * @param {String} oldClassName the class name to be replaced
491 * @param {String} newClassName the class name that will be replacing the old class name
492 * @return {Boolean | Array} A pass/fail boolean or array of booleans
494 replaceClass: function(el, oldClassName, newClassName) {
495 if (!newClassName || oldClassName === newClassName) { // avoid infinite loop
499 var re = getClassRegEx(oldClassName);
501 var f = function(el) {
503 if ( !this.hasClass(el, oldClassName) ) {
504 this.addClass(el, newClassName); // just add it if nothing to replace
505 return true; // NOTE: return
508 el.className = el.className.replace(re, ' ' + newClassName + ' ');
510 if ( this.hasClass(el, oldClassName) ) { // in case of multiple adjacent
511 this.removeClass(el, oldClassName);
514 el.className = lang.trim(el.className); // remove any trailing spaces
518 return Y.Dom.batch(el, f, Y.Dom, true);
522 * Returns an ID and applies it to the element "el", if provided.
524 * @param {String | HTMLElement | Array} el (optional) An optional element array of elements to add an ID to (no ID is added if one is already present).
525 * @param {String} prefix (optional) an optional prefix to use (defaults to "yui-gen").
526 * @return {String | Array} The generated ID, or array of generated IDs (or original ID if already present on an element)
528 generateId: function(el, prefix) {
529 prefix = prefix || 'yui-gen';
531 var f = function(el) {
532 if (el && el.id) { // do not override existing ID
536 var id = prefix + YAHOO.env._id_counter++;
545 // batch fails when no element, so just generate and return single ID
546 return Y.Dom.batch(el, f, Y.Dom, true) || f.apply(Y.Dom, arguments);
550 * Determines whether an HTMLElement is an ancestor of another HTML element in the DOM hierarchy.
552 * @param {String | HTMLElement} haystack The possible ancestor
553 * @param {String | HTMLElement} needle The possible descendent
554 * @return {Boolean} Whether or not the haystack is an ancestor of needle
556 isAncestor: function(haystack, needle) {
557 haystack = Y.Dom.get(haystack);
558 needle = Y.Dom.get(needle);
562 if ( (haystack && needle) && (haystack.nodeType && needle.nodeType) ) {
563 if (haystack.contains && haystack !== needle) { // contains returns true when equal
564 ret = haystack.contains(needle);
566 else if (haystack.compareDocumentPosition) { // gecko
567 ret = !!(haystack.compareDocumentPosition(needle) & 16);
575 * Determines whether an HTMLElement is present in the current document.
577 * @param {String | HTMLElement} el The element to search for
578 * @return {Boolean} Whether or not the element is present in the current document
580 inDocument: function(el) {
581 return this.isAncestor(document.documentElement, el);
585 * Returns a array of HTMLElements that pass the test applied by supplied boolean method.
586 * For optimized performance, include a tag and/or root node when possible.
587 * Note: This method operates against a live collection, so modifying the
588 * collection in the callback (removing/appending nodes, etc.) will have
589 * side effects. Instead you should iterate the returned nodes array,
590 * as you would with the native "getElementsByTagName" method.
591 * @method getElementsBy
592 * @param {Function} method - A boolean method for testing elements which receives the element as its only argument.
593 * @param {String} tag (optional) The tag name of the elements being collected
594 * @param {String | HTMLElement} root (optional) The HTMLElement or an ID to use as the starting point
595 * @param {Function} apply (optional) A function to apply to each element when found
596 * @return {Array} Array of HTMLElements
598 getElementsBy: function(method, tag, root, apply) {
600 root = (root) ? Y.Dom.get(root) : null || document;
607 elements = root.getElementsByTagName(tag);
609 for (var i = 0, len = elements.length; i < len; ++i) {
610 if ( method(elements[i]) ) {
611 nodes[nodes.length] = elements[i];
623 * Runs the supplied method against each item in the Collection/Array.
624 * The method is called with the element(s) as the first arg, and the optional param as the second ( method(el, o) ).
626 * @param {String | HTMLElement | Array} el (optional) An element or array of elements to apply the method to
627 * @param {Function} method The method to apply to the element(s)
628 * @param {Any} o (optional) An optional arg that is passed to the supplied method
629 * @param {Boolean} override (optional) Whether or not to override the scope of "method" with "o"
630 * @return {Any | Array} The return value(s) from the supplied method
632 batch: function(el, method, o, override) {
633 el = (el && (el.tagName || el.item)) ? el : Y.Dom.get(el); // skip get() when possible
635 if (!el || !method) {
638 var scope = (override) ? o : window;
640 if (el.tagName || el.length === undefined) { // element or not array-like
641 return method.call(scope, el, o);
646 for (var i = 0, len = el.length; i < len; ++i) {
647 collection[collection.length] = method.call(scope, el[i], o);
654 * Returns the height of the document.
655 * @method getDocumentHeight
656 * @return {Int} The height of the actual document (which includes the body and its margin).
658 getDocumentHeight: function() {
659 var scrollHeight = (document.compatMode != 'CSS1Compat') ? document.body.scrollHeight : document.documentElement.scrollHeight;
661 var h = Math.max(scrollHeight, Y.Dom.getViewportHeight());
666 * Returns the width of the document.
667 * @method getDocumentWidth
668 * @return {Int} The width of the actual document (which includes the body and its margin).
670 getDocumentWidth: function() {
671 var scrollWidth = (document.compatMode != 'CSS1Compat') ? document.body.scrollWidth : document.documentElement.scrollWidth;
672 var w = Math.max(scrollWidth, Y.Dom.getViewportWidth());
677 * Returns the current height of the viewport.
678 * @method getViewportHeight
679 * @return {Int} The height of the viewable area of the page (excludes scrollbars).
681 getViewportHeight: function() {
682 var height = self.innerHeight; // Safari, Opera
683 var mode = document.compatMode;
685 if ( (mode || isIE) && !isOpera ) { // IE, Gecko
686 height = (mode == 'CSS1Compat') ?
687 document.documentElement.clientHeight : // Standards
688 document.body.clientHeight; // Quirks
695 * Returns the current width of the viewport.
696 * @method getViewportWidth
697 * @return {Int} The width of the viewable area of the page (excludes scrollbars).
700 getViewportWidth: function() {
701 var width = self.innerWidth; // Safari
702 var mode = document.compatMode;
704 if (mode || isIE) { // IE, Gecko, Opera
705 width = (mode == 'CSS1Compat') ?
706 document.documentElement.clientWidth : // Standards
707 document.body.clientWidth; // Quirks
713 * Returns the nearest ancestor that passes the test applied by supplied boolean method.
714 * For performance reasons, IDs are not accepted and argument validation omitted.
715 * @method getAncestorBy
716 * @param {HTMLElement} node The HTMLElement to use as the starting point
717 * @param {Function} method - A boolean method for testing elements which receives the element as its only argument.
718 * @return {Object} HTMLElement or null if not found
720 getAncestorBy: function(node, method) {
721 while ( (node = node.parentNode) ) { // NOTE: assignment
722 if ( testElement(node, method) ) {
731 * Returns the nearest ancestor with the given className.
732 * @method getAncestorByClassName
733 * @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point
734 * @param {String} className
735 * @return {Object} HTMLElement
737 getAncestorByClassName: function(node, className) {
738 node = Y.Dom.get(node);
742 var method = function(el) { return Y.Dom.hasClass(el, className); };
743 return Y.Dom.getAncestorBy(node, method);
747 * Returns the nearest ancestor with the given tagName.
748 * @method getAncestorByTagName
749 * @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point
750 * @param {String} tagName
751 * @return {Object} HTMLElement
753 getAncestorByTagName: function(node, tagName) {
754 node = Y.Dom.get(node);
758 var method = function(el) {
759 return el.tagName && el.tagName.toUpperCase() == tagName.toUpperCase();
762 return Y.Dom.getAncestorBy(node, method);
766 * Returns the previous sibling that is an HTMLElement.
767 * For performance reasons, IDs are not accepted and argument validation omitted.
768 * Returns the nearest HTMLElement sibling if no method provided.
769 * @method getPreviousSiblingBy
770 * @param {HTMLElement} node The HTMLElement to use as the starting point
771 * @param {Function} method A boolean function used to test siblings
772 * that receives the sibling node being tested as its only argument
773 * @return {Object} HTMLElement or null if not found
775 getPreviousSiblingBy: function(node, method) {
777 node = node.previousSibling;
778 if ( testElement(node, method) ) {
786 * Returns the previous sibling that is an HTMLElement
787 * @method getPreviousSibling
788 * @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point
789 * @return {Object} HTMLElement or null if not found
791 getPreviousSibling: function(node) {
792 node = Y.Dom.get(node);
797 return Y.Dom.getPreviousSiblingBy(node);
801 * Returns the next HTMLElement sibling that passes the boolean method.
802 * For performance reasons, IDs are not accepted and argument validation omitted.
803 * Returns the nearest HTMLElement sibling if no method provided.
804 * @method getNextSiblingBy
805 * @param {HTMLElement} node The HTMLElement to use as the starting point
806 * @param {Function} method A boolean function used to test siblings
807 * that receives the sibling node being tested as its only argument
808 * @return {Object} HTMLElement or null if not found
810 getNextSiblingBy: function(node, method) {
812 node = node.nextSibling;
813 if ( testElement(node, method) ) {
821 * Returns the next sibling that is an HTMLElement
822 * @method getNextSibling
823 * @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point
824 * @return {Object} HTMLElement or null if not found
826 getNextSibling: function(node) {
827 node = Y.Dom.get(node);
832 return Y.Dom.getNextSiblingBy(node);
836 * Returns the first HTMLElement child that passes the test method.
837 * @method getFirstChildBy
838 * @param {HTMLElement} node The HTMLElement to use as the starting point
839 * @param {Function} method A boolean function used to test children
840 * that receives the node being tested as its only argument
841 * @return {Object} HTMLElement or null if not found
843 getFirstChildBy: function(node, method) {
844 var child = ( testElement(node.firstChild, method) ) ? node.firstChild : null;
845 return child || Y.Dom.getNextSiblingBy(node.firstChild, method);
849 * Returns the first HTMLElement child.
850 * @method getFirstChild
851 * @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point
852 * @return {Object} HTMLElement or null if not found
854 getFirstChild: function(node, method) {
855 node = Y.Dom.get(node);
859 return Y.Dom.getFirstChildBy(node);
863 * Returns the last HTMLElement child that passes the test method.
864 * @method getLastChildBy
865 * @param {HTMLElement} node The HTMLElement to use as the starting point
866 * @param {Function} method A boolean function used to test children
867 * that receives the node being tested as its only argument
868 * @return {Object} HTMLElement or null if not found
870 getLastChildBy: function(node, method) {
874 var child = ( testElement(node.lastChild, method) ) ? node.lastChild : null;
875 return child || Y.Dom.getPreviousSiblingBy(node.lastChild, method);
879 * Returns the last HTMLElement child.
880 * @method getLastChild
881 * @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point
882 * @return {Object} HTMLElement or null if not found
884 getLastChild: function(node) {
885 node = Y.Dom.get(node);
886 return Y.Dom.getLastChildBy(node);
890 * Returns an array of HTMLElement childNodes that pass the test method.
891 * @method getChildrenBy
892 * @param {HTMLElement} node The HTMLElement to start from
893 * @param {Function} method A boolean function used to test children
894 * that receives the node being tested as its only argument
895 * @return {Array} A static array of HTMLElements
897 getChildrenBy: function(node, method) {
898 var child = Y.Dom.getFirstChildBy(node, method);
899 var children = child ? [child] : [];
901 Y.Dom.getNextSiblingBy(child, function(node) {
902 if ( !method || method(node) ) {
903 children[children.length] = node;
905 return false; // fail test to collect all children
912 * Returns an array of HTMLElement childNodes.
913 * @method getChildren
914 * @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point
915 * @return {Array} A static array of HTMLElements
917 getChildren: function(node) {
918 node = Y.Dom.get(node);
922 return Y.Dom.getChildrenBy(node);
926 * Returns the left scroll value of the document
927 * @method getDocumentScrollLeft
928 * @param {HTMLDocument} document (optional) The document to get the scroll value of
929 * @return {Int} The amount that the document is scrolled to the left
931 getDocumentScrollLeft: function(doc) {
932 doc = doc || document;
933 return Math.max(doc.documentElement.scrollLeft, doc.body.scrollLeft);
937 * Returns the top scroll value of the document
938 * @method getDocumentScrollTop
939 * @param {HTMLDocument} document (optional) The document to get the scroll value of
940 * @return {Int} The amount that the document is scrolled to the top
942 getDocumentScrollTop: function(doc) {
943 doc = doc || document;
944 return Math.max(doc.documentElement.scrollTop, doc.body.scrollTop);
948 * Inserts the new node as the previous sibling of the reference node
949 * @method insertBefore
950 * @param {String | HTMLElement} newNode The node to be inserted
951 * @param {String | HTMLElement} referenceNode The node to insert the new node before
952 * @return {HTMLElement} The node that was inserted (or null if insert fails)
954 insertBefore: function(newNode, referenceNode) {
955 newNode = Y.Dom.get(newNode);
956 referenceNode = Y.Dom.get(referenceNode);
958 if (!newNode || !referenceNode || !referenceNode.parentNode) {
962 return referenceNode.parentNode.insertBefore(newNode, referenceNode);
966 * Inserts the new node as the next sibling of the reference node
967 * @method insertAfter
968 * @param {String | HTMLElement} newNode The node to be inserted
969 * @param {String | HTMLElement} referenceNode The node to insert the new node after
970 * @return {HTMLElement} The node that was inserted (or null if insert fails)
972 insertAfter: function(newNode, referenceNode) {
973 newNode = Y.Dom.get(newNode);
974 referenceNode = Y.Dom.get(referenceNode);
976 if (!newNode || !referenceNode || !referenceNode.parentNode) {
980 if (referenceNode.nextSibling) {
981 return referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
983 return referenceNode.parentNode.appendChild(newNode);
988 * Creates a Region based on the viewport relative to the document.
989 * @method getClientRegion
990 * @return {Region} A Region object representing the viewport which accounts for document scroll
992 getClientRegion: function() {
993 var t = Y.Dom.getDocumentScrollTop(),
994 l = Y.Dom.getDocumentScrollLeft(),
995 r = Y.Dom.getViewportWidth() + l,
996 b = Y.Dom.getViewportHeight() + t;
998 return new Y.Region(t, r, b, l);
1002 var getXY = function() {
1003 if (document.documentElement.getBoundingClientRect) { // IE
1004 return function(el) {
1005 var box = el.getBoundingClientRect(),
1008 var rootNode = el.ownerDocument;
1009 return [round(box.left + Y.Dom.getDocumentScrollLeft(rootNode)), round(box.top +
1010 Y.Dom.getDocumentScrollTop(rootNode))];
1013 return function(el) { // manually calculate by crawling up offsetParents
1014 var pos = [el.offsetLeft, el.offsetTop];
1015 var parentNode = el.offsetParent;
1017 // safari: subtract body offsets if el is abs (or any offsetParent), unless body is offsetParent
1018 var accountForBody = (isSafari &&
1019 Y.Dom.getStyle(el, 'position') == 'absolute' &&
1020 el.offsetParent == el.ownerDocument.body);
1022 if (parentNode != el) {
1023 while (parentNode) {
1024 pos[0] += parentNode.offsetLeft;
1025 pos[1] += parentNode.offsetTop;
1026 if (!accountForBody && isSafari &&
1027 Y.Dom.getStyle(parentNode,'position') == 'absolute' ) {
1028 accountForBody = true;
1030 parentNode = parentNode.offsetParent;
1034 if (accountForBody) { //safari doubles in this case
1035 pos[0] -= el.ownerDocument.body.offsetLeft;
1036 pos[1] -= el.ownerDocument.body.offsetTop;
1038 parentNode = el.parentNode;
1040 // account for any scrolled ancestors
1041 while ( parentNode.tagName && !patterns.ROOT_TAG.test(parentNode.tagName) )
1043 if (parentNode.scrollTop || parentNode.scrollLeft) {
1044 pos[0] -= parentNode.scrollLeft;
1045 pos[1] -= parentNode.scrollTop;
1048 parentNode = parentNode.parentNode;
1054 }() // NOTE: Executing for loadtime branching
1057 * A region is a representation of an object on a grid. It is defined
1058 * by the top, right, bottom, left extents, so is rectangular by default. If
1059 * other shapes are required, this class could be extended to support it.
1060 * @namespace YAHOO.util
1062 * @param {Int} t the top extent
1063 * @param {Int} r the right extent
1064 * @param {Int} b the bottom extent
1065 * @param {Int} l the left extent
1068 YAHOO.util.Region = function(t, r, b, l) {
1071 * The region's top extent
1078 * The region's top extent as index, for symmetry with set/getXY
1085 * The region's right extent
1092 * The region's bottom extent
1099 * The region's left extent
1106 * The region's left extent as index, for symmetry with set/getXY
1114 * Returns true if this region contains the region passed in
1116 * @param {Region} region The region to evaluate
1117 * @return {Boolean} True if the region is contained with this region,
1120 YAHOO.util.Region.prototype.contains = function(region) {
1121 return ( region.left >= this.left &&
1122 region.right <= this.right &&
1123 region.top >= this.top &&
1124 region.bottom <= this.bottom );
1129 * Returns the area of the region
1131 * @return {Int} the region's area
1133 YAHOO.util.Region.prototype.getArea = function() {
1134 return ( (this.bottom - this.top) * (this.right - this.left) );
1138 * Returns the region where the passed in region overlaps with this one
1140 * @param {Region} region The region that intersects
1141 * @return {Region} The overlap region, or null if there is no overlap
1143 YAHOO.util.Region.prototype.intersect = function(region) {
1144 var t = Math.max( this.top, region.top );
1145 var r = Math.min( this.right, region.right );
1146 var b = Math.min( this.bottom, region.bottom );
1147 var l = Math.max( this.left, region.left );
1149 if (b >= t && r >= l) {
1150 return new YAHOO.util.Region(t, r, b, l);
1157 * Returns the region representing the smallest region that can contain both
1158 * the passed in region and this region.
1160 * @param {Region} region The region that to create the union with
1161 * @return {Region} The union region
1163 YAHOO.util.Region.prototype.union = function(region) {
1164 var t = Math.min( this.top, region.top );
1165 var r = Math.max( this.right, region.right );
1166 var b = Math.max( this.bottom, region.bottom );
1167 var l = Math.min( this.left, region.left );
1169 return new YAHOO.util.Region(t, r, b, l);
1175 * @return string the region properties
1177 YAHOO.util.Region.prototype.toString = function() {
1178 return ( "Region {" +
1179 "top: " + this.top +
1180 ", right: " + this.right +
1181 ", bottom: " + this.bottom +
1182 ", left: " + this.left +
1187 * Returns a region that is occupied by the DOM element
1189 * @param {HTMLElement} el The element
1190 * @return {Region} The region that the element occupies
1193 YAHOO.util.Region.getRegion = function(el) {
1194 var p = YAHOO.util.Dom.getXY(el);
1197 var r = p[0] + el.offsetWidth;
1198 var b = p[1] + el.offsetHeight;
1201 return new YAHOO.util.Region(t, r, b, l);
1204 /////////////////////////////////////////////////////////////////////////////
1208 * A point is a region that is special in that it represents a single point on
1210 * @namespace YAHOO.util
1212 * @param {Int} x The X position of the point
1213 * @param {Int} y The Y position of the point
1215 * @extends YAHOO.util.Region
1217 YAHOO.util.Point = function(x, y) {
1218 if (YAHOO.lang.isArray(x)) { // accept input from Dom.getXY, Event.getXY, etc.
1219 y = x[1]; // dont blow away x yet
1224 * The X position of the point, which is also the right, left and index zero (for Dom.getXY symmetry)
1229 this.x = this.right = this.left = this[0] = x;
1232 * The Y position of the point, which is also the top, bottom and index one (for Dom.getXY symmetry)
1236 this.y = this.top = this.bottom = this[1] = y;
1239 YAHOO.util.Point.prototype = new YAHOO.util.Region();
1241 YAHOO.register("dom", YAHOO.util.Dom, {version: "2.6.0", build: "1321"});