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
15 getStyle, // for load time browser branching
17 propertyCache = {}, // for faster hyphen converts
18 reClassNameCache = {}, // cache regexes for className
19 document = window.document; // cache for faster lookups
21 YAHOO.env._id_counter = YAHOO.env._id_counter || 0; // for use with generateId (global to save state if Dom is overwritten)
24 var isOpera = YAHOO.env.ua.opera,
25 isSafari = YAHOO.env.ua.webkit,
26 isGecko = YAHOO.env.ua.gecko,
27 isIE = YAHOO.env.ua.ie;
31 HYPHEN: /(-[a-z])/i, // to normalize get/setStyle
32 ROOT_TAG: /^body|html$/i, // body for quirks mode, html for standards,
33 OP_SCROLL:/^(?:inline|table-row)$/i
36 var toCamel = function(property) {
37 if ( !patterns.HYPHEN.test(property) ) {
38 return property; // no hyphens
41 if (propertyCache[property]) { // already converted
42 return propertyCache[property];
45 var converted = property;
47 while( patterns.HYPHEN.exec(converted) ) {
48 converted = converted.replace(RegExp.$1,
49 RegExp.$1.substr(1).toUpperCase());
52 propertyCache[property] = converted;
54 //return property.replace(/-([a-z])/gi, function(m0, m1) {return m1.toUpperCase()}) // cant use function as 2nd arg yet due to safari bug
57 var getClassRegEx = function(className) {
58 var re = reClassNameCache[className];
60 re = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)');
61 reClassNameCache[className] = re;
66 // branching at load instead of runtime
67 if (document.defaultView && document.defaultView.getComputedStyle) { // W3C DOM method
68 getStyle = function(el, property) {
71 if (property == 'float') { // fix reserved word
72 property = 'cssFloat';
75 var computed = el.ownerDocument.defaultView.getComputedStyle(el, '');
76 if (computed) { // test computed before touching for safari
77 value = computed[toCamel(property)];
80 return el.style[property] || value;
82 } else if (document.documentElement.currentStyle && isIE) { // IE method
83 getStyle = function(el, property) {
84 switch( toCamel(property) ) {
85 case 'opacity' :// IE opacity uses filter
87 try { // will error if no DXImageTransform
88 val = el.filters['DXImageTransform.Microsoft.Alpha'].opacity;
91 try { // make sure its in the document
92 val = el.filters('alpha').opacity;
97 case 'float': // fix reserved word
98 property = 'styleFloat'; // fall through
100 // test currentStyle before touching
101 var value = el.currentStyle ? el.currentStyle[property] : null;
102 return ( el.style[property] || value );
105 } else { // default to inline only
106 getStyle = function(el, property) { return el.style[property]; };
110 setStyle = function(el, property, val) {
113 if ( YAHOO.lang.isString(el.style.filter) ) { // in case not appended
114 el.style.filter = 'alpha(opacity=' + val * 100 + ')';
116 if (!el.currentStyle || !el.currentStyle.hasLayout) {
117 el.style.zoom = 1; // when no layout or cant tell
122 property = 'styleFloat';
124 el.style[property] = val;
128 setStyle = function(el, property, val) {
129 if (property == 'float') {
130 property = 'cssFloat';
132 el.style[property] = val;
136 var testElement = function(node, method) {
137 return node && node.nodeType == 1 && ( !method || method(node) );
141 * Provides helper methods for DOM elements.
142 * @namespace YAHOO.util
147 * Returns an HTMLElement reference.
149 * @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.
150 * @return {HTMLElement | Array} A DOM reference to an HTML element or an array of HTMLElements.
153 if (el && (el.nodeType || el.item)) { // Node, or NodeList
157 if (YAHOO.lang.isString(el) || !el) { // id or null
158 return document.getElementById(el);
161 if (el.length !== undefined) { // array-like
163 for (var i = 0, len = el.length; i < len; ++i) {
164 c[c.length] = Y.Dom.get(el[i]);
170 return el; // some other object, just pass it back
174 * Normalizes currentStyle and ComputedStyle.
176 * @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.
177 * @param {String} property The style property whose value is returned.
178 * @return {String | Array} The current value of the style property for the element(s).
180 getStyle: function(el, property) {
181 property = toCamel(property);
183 var f = function(element) {
184 return getStyle(element, property);
187 return Y.Dom.batch(el, f, Y.Dom, true);
191 * Wrapper for setting style properties of HTMLElements. Normalizes "opacity" across modern browsers.
193 * @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.
194 * @param {String} property The style property to be set.
195 * @param {String} val The value to apply to the given property.
197 setStyle: function(el, property, val) {
198 property = toCamel(property);
200 var f = function(element) {
201 setStyle(element, property, val);
205 Y.Dom.batch(el, f, Y.Dom, true);
209 * 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).
211 * @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
212 * @return {Array} The XY position of the element(s)
214 getXY: function(el) {
215 var f = function(el) {
216 // has to be part of document to have pageXY
217 if ( (el.parentNode === null || el.offsetParent === null ||
218 this.getStyle(el, 'display') == 'none') && el != el.ownerDocument.body) {
225 return Y.Dom.batch(el, f, Y.Dom, true);
229 * 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).
231 * @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
232 * @return {Number | Array} The X position of the element(s)
235 var f = function(el) {
236 return Y.Dom.getXY(el)[0];
239 return Y.Dom.batch(el, f, Y.Dom, true);
243 * 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).
245 * @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
246 * @return {Number | Array} The Y position of the element(s)
249 var f = function(el) {
250 return Y.Dom.getXY(el)[1];
253 return Y.Dom.batch(el, f, Y.Dom, true);
257 * Set the position of an html element in page coordinates, regardless of how the element is positioned.
258 * The element(s) must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
260 * @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
261 * @param {Array} pos Contains X & Y values for new position (coordinates are page-based)
262 * @param {Boolean} noRetry By default we try and set the position a second time if the first fails
264 setXY: function(el, pos, noRetry) {
265 var f = function(el) {
266 var style_pos = this.getStyle(el, 'position');
267 if (style_pos == 'static') { // default to relative
268 this.setStyle(el, 'position', 'relative');
269 style_pos = 'relative';
272 var pageXY = this.getXY(el);
273 if (pageXY === false) { // has to be part of doc to have pageXY
277 var delta = [ // assuming pixels; if not we will have to retry
278 parseInt( this.getStyle(el, 'left'), 10 ),
279 parseInt( this.getStyle(el, 'top'), 10 )
282 if ( isNaN(delta[0]) ) {// in case of 'auto'
283 delta[0] = (style_pos == 'relative') ? 0 : el.offsetLeft;
285 if ( isNaN(delta[1]) ) { // in case of 'auto'
286 delta[1] = (style_pos == 'relative') ? 0 : el.offsetTop;
289 if (pos[0] !== null) { el.style.left = pos[0] - pageXY[0] + delta[0] + 'px'; }
290 if (pos[1] !== null) { el.style.top = pos[1] - pageXY[1] + delta[1] + 'px'; }
293 var newXY = this.getXY(el);
295 // if retry is true, try one more time if we miss
296 if ( (pos[0] !== null && newXY[0] != pos[0]) ||
297 (pos[1] !== null && newXY[1] != pos[1]) ) {
298 this.setXY(el, pos, true);
304 Y.Dom.batch(el, f, Y.Dom, true);
308 * Set the X position of an html element in page coordinates, regardless of how the element is positioned.
309 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
311 * @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.
312 * @param {Int} x The value to use as the X coordinate for the element(s).
314 setX: function(el, x) {
315 Y.Dom.setXY(el, [x, null]);
319 * Set the Y position of an html element in page coordinates, regardless of how the element is positioned.
320 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
322 * @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.
323 * @param {Int} x To use as the Y coordinate for the element(s).
325 setY: function(el, y) {
326 Y.Dom.setXY(el, [null, y]);
330 * Returns the region position of the given element.
331 * The element must be part of the DOM tree to have a region (display:none or elements not appended return false).
333 * @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.
334 * @return {Region | Array} A Region or array of Region instances containing "top, left, bottom, right" member data.
336 getRegion: function(el) {
337 var f = function(el) {
338 if ( (el.parentNode === null || el.offsetParent === null ||
339 this.getStyle(el, 'display') == 'none') && el != el.ownerDocument.body) {
343 var region = Y.Region.getRegion(el);
347 return Y.Dom.batch(el, f, Y.Dom, true);
351 * Returns the width of the client (viewport).
352 * @method getClientWidth
353 * @deprecated Now using getViewportWidth. This interface left intact for back compat.
354 * @return {Int} The width of the viewable area of the page.
356 getClientWidth: function() {
357 return Y.Dom.getViewportWidth();
361 * Returns the height of the client (viewport).
362 * @method getClientHeight
363 * @deprecated Now using getViewportHeight. This interface left intact for back compat.
364 * @return {Int} The height of the viewable area of the page.
366 getClientHeight: function() {
367 return Y.Dom.getViewportHeight();
371 * Returns a array of HTMLElements with the given class.
372 * For optimized performance, include a tag and/or root node when possible.
373 * @method getElementsByClassName
374 * @param {String} className The class name to match against
375 * @param {String} tag (optional) The tag name of the elements being collected
376 * @param {String | HTMLElement} root (optional) The HTMLElement or an ID to use as the starting point
377 * @param {Function} apply (optional) A function to apply to each element when found
378 * @return {Array} An array of elements that have the given class name
380 getElementsByClassName: function(className, tag, root, apply) {
382 root = (root) ? Y.Dom.get(root) : null || document;
388 elements = root.getElementsByTagName(tag),
389 re = getClassRegEx(className);
391 for (var i = 0, len = elements.length; i < len; ++i) {
392 if ( re.test(elements[i].className) ) {
393 nodes[nodes.length] = elements[i];
395 apply.call(elements[i], elements[i]);
404 * Determines whether an HTMLElement has the given className.
406 * @param {String | HTMLElement | Array} el The element or collection to test
407 * @param {String} className the class name to search for
408 * @return {Boolean | Array} A boolean value or array of boolean values
410 hasClass: function(el, className) {
411 var re = getClassRegEx(className);
413 var f = function(el) {
414 return re.test(el.className);
417 return Y.Dom.batch(el, f, Y.Dom, true);
421 * Adds a class name to a given element or collection of elements.
423 * @param {String | HTMLElement | Array} el The element or collection to add the class to
424 * @param {String} className the class name to add to the class attribute
425 * @return {Boolean | Array} A pass/fail boolean or array of booleans
427 addClass: function(el, className) {
428 var f = function(el) {
429 if (this.hasClass(el, className)) {
430 return false; // already present
434 el.className = YAHOO.lang.trim([el.className, className].join(' '));
438 return Y.Dom.batch(el, f, Y.Dom, true);
442 * Removes a class name from a given element or collection of elements.
443 * @method removeClass
444 * @param {String | HTMLElement | Array} el The element or collection to remove the class from
445 * @param {String} className the class name to remove from the class attribute
446 * @return {Boolean | Array} A pass/fail boolean or array of booleans
448 removeClass: function(el, className) {
449 var re = getClassRegEx(className);
451 var f = function(el) {
452 if (!className || !this.hasClass(el, className)) {
453 return false; // not present
457 var c = el.className;
458 el.className = c.replace(re, ' ');
459 if ( this.hasClass(el, className) ) { // in case of multiple adjacent
460 this.removeClass(el, className);
463 el.className = YAHOO.lang.trim(el.className); // remove any trailing spaces
467 return Y.Dom.batch(el, f, Y.Dom, true);
471 * Replace a class with another class for a given element or collection of elements.
472 * If no oldClassName is present, the newClassName is simply added.
473 * @method replaceClass
474 * @param {String | HTMLElement | Array} el The element or collection to remove the class from
475 * @param {String} oldClassName the class name to be replaced
476 * @param {String} newClassName the class name that will be replacing the old class name
477 * @return {Boolean | Array} A pass/fail boolean or array of booleans
479 replaceClass: function(el, oldClassName, newClassName) {
480 if (!newClassName || oldClassName === newClassName) { // avoid infinite loop
484 var re = getClassRegEx(oldClassName);
486 var f = function(el) {
488 if ( !this.hasClass(el, oldClassName) ) {
489 this.addClass(el, newClassName); // just add it if nothing to replace
490 return true; // NOTE: return
493 el.className = el.className.replace(re, ' ' + newClassName + ' ');
495 if ( this.hasClass(el, oldClassName) ) { // in case of multiple adjacent
496 this.replaceClass(el, oldClassName, newClassName);
499 el.className = YAHOO.lang.trim(el.className); // remove any trailing spaces
503 return Y.Dom.batch(el, f, Y.Dom, true);
507 * Returns an ID and applies it to the element "el", if provided.
509 * @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).
510 * @param {String} prefix (optional) an optional prefix to use (defaults to "yui-gen").
511 * @return {String | Array} The generated ID, or array of generated IDs (or original ID if already present on an element)
513 generateId: function(el, prefix) {
514 prefix = prefix || 'yui-gen';
516 var f = function(el) {
517 if (el && el.id) { // do not override existing ID
521 var id = prefix + YAHOO.env._id_counter++;
530 // batch fails when no element, so just generate and return single ID
531 return Y.Dom.batch(el, f, Y.Dom, true) || f.apply(Y.Dom, arguments);
535 * Determines whether an HTMLElement is an ancestor of another HTML element in the DOM hierarchy.
537 * @param {String | HTMLElement} haystack The possible ancestor
538 * @param {String | HTMLElement} needle The possible descendent
539 * @return {Boolean} Whether or not the haystack is an ancestor of needle
541 isAncestor: function(haystack, needle) {
542 haystack = Y.Dom.get(haystack);
543 needle = Y.Dom.get(needle);
545 if (!haystack || !needle) {
549 if (haystack.contains && needle.nodeType && !isSafari) { // safari contains is broken
550 return haystack.contains(needle);
552 else if ( haystack.compareDocumentPosition && needle.nodeType ) {
553 return !!(haystack.compareDocumentPosition(needle) & 16);
554 } else if (needle.nodeType) {
555 // fallback to crawling up (safari)
556 return !!this.getAncestorBy(needle, function(el) {
557 return el == haystack;
564 * Determines whether an HTMLElement is present in the current document.
566 * @param {String | HTMLElement} el The element to search for
567 * @return {Boolean} Whether or not the element is present in the current document
569 inDocument: function(el) {
570 return this.isAncestor(document.documentElement, el);
574 * Returns a array of HTMLElements that pass the test applied by supplied boolean method.
575 * For optimized performance, include a tag and/or root node when possible.
576 * @method getElementsBy
577 * @param {Function} method - A boolean method for testing elements which receives the element as its only argument.
578 * @param {String} tag (optional) The tag name of the elements being collected
579 * @param {String | HTMLElement} root (optional) The HTMLElement or an ID to use as the starting point
580 * @param {Function} apply (optional) A function to apply to each element when found
581 * @return {Array} Array of HTMLElements
583 getElementsBy: function(method, tag, root, apply) {
585 root = (root) ? Y.Dom.get(root) : null || document;
592 elements = root.getElementsByTagName(tag);
594 for (var i = 0, len = elements.length; i < len; ++i) {
595 if ( method(elements[i]) ) {
596 nodes[nodes.length] = elements[i];
608 * Runs the supplied method against each item in the Collection/Array.
609 * The method is called with the element(s) as the first arg, and the optional param as the second ( method(el, o) ).
611 * @param {String | HTMLElement | Array} el (optional) An element or array of elements to apply the method to
612 * @param {Function} method The method to apply to the element(s)
613 * @param {Any} o (optional) An optional arg that is passed to the supplied method
614 * @param {Boolean} override (optional) Whether or not to override the scope of "method" with "o"
615 * @return {Any | Array} The return value(s) from the supplied method
617 batch: function(el, method, o, override) {
618 el = (el && (el.tagName || el.item)) ? el : Y.Dom.get(el); // skip get() when possible
620 if (!el || !method) {
623 var scope = (override) ? o : window;
625 if (el.tagName || el.length === undefined) { // element or not array-like
626 return method.call(scope, el, o);
631 for (var i = 0, len = el.length; i < len; ++i) {
632 collection[collection.length] = method.call(scope, el[i], o);
639 * Returns the height of the document.
640 * @method getDocumentHeight
641 * @return {Int} The height of the actual document (which includes the body and its margin).
643 getDocumentHeight: function() {
644 var scrollHeight = (document.compatMode != 'CSS1Compat') ? document.body.scrollHeight : document.documentElement.scrollHeight;
646 var h = Math.max(scrollHeight, Y.Dom.getViewportHeight());
651 * Returns the width of the document.
652 * @method getDocumentWidth
653 * @return {Int} The width of the actual document (which includes the body and its margin).
655 getDocumentWidth: function() {
656 var scrollWidth = (document.compatMode != 'CSS1Compat') ? document.body.scrollWidth : document.documentElement.scrollWidth;
657 var w = Math.max(scrollWidth, Y.Dom.getViewportWidth());
662 * Returns the current height of the viewport.
663 * @method getViewportHeight
664 * @return {Int} The height of the viewable area of the page (excludes scrollbars).
666 getViewportHeight: function() {
667 var height = self.innerHeight; // Safari, Opera
668 var mode = document.compatMode;
670 if ( (mode || isIE) && !isOpera ) { // IE, Gecko
671 height = (mode == 'CSS1Compat') ?
672 document.documentElement.clientHeight : // Standards
673 document.body.clientHeight; // Quirks
680 * Returns the current width of the viewport.
681 * @method getViewportWidth
682 * @return {Int} The width of the viewable area of the page (excludes scrollbars).
685 getViewportWidth: function() {
686 var width = self.innerWidth; // Safari
687 var mode = document.compatMode;
689 if (mode || isIE) { // IE, Gecko, Opera
690 width = (mode == 'CSS1Compat') ?
691 document.documentElement.clientWidth : // Standards
692 document.body.clientWidth; // Quirks
698 * Returns the nearest ancestor that passes the test applied by supplied boolean method.
699 * For performance reasons, IDs are not accepted and argument validation omitted.
700 * @method getAncestorBy
701 * @param {HTMLElement} node The HTMLElement to use as the starting point
702 * @param {Function} method - A boolean method for testing elements which receives the element as its only argument.
703 * @return {Object} HTMLElement or null if not found
705 getAncestorBy: function(node, method) {
706 while (node = node.parentNode) { // NOTE: assignment
707 if ( testElement(node, method) ) {
716 * Returns the nearest ancestor with the given className.
717 * @method getAncestorByClassName
718 * @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point
719 * @param {String} className
720 * @return {Object} HTMLElement
722 getAncestorByClassName: function(node, className) {
723 node = Y.Dom.get(node);
727 var method = function(el) { return Y.Dom.hasClass(el, className); };
728 return Y.Dom.getAncestorBy(node, method);
732 * Returns the nearest ancestor with the given tagName.
733 * @method getAncestorByTagName
734 * @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point
735 * @param {String} tagName
736 * @return {Object} HTMLElement
738 getAncestorByTagName: function(node, tagName) {
739 node = Y.Dom.get(node);
743 var method = function(el) {
744 return el.tagName && el.tagName.toUpperCase() == tagName.toUpperCase();
747 return Y.Dom.getAncestorBy(node, method);
751 * Returns the previous sibling that is an HTMLElement.
752 * For performance reasons, IDs are not accepted and argument validation omitted.
753 * Returns the nearest HTMLElement sibling if no method provided.
754 * @method getPreviousSiblingBy
755 * @param {HTMLElement} node The HTMLElement to use as the starting point
756 * @param {Function} method A boolean function used to test siblings
757 * that receives the sibling node being tested as its only argument
758 * @return {Object} HTMLElement or null if not found
760 getPreviousSiblingBy: function(node, method) {
762 node = node.previousSibling;
763 if ( testElement(node, method) ) {
771 * Returns the previous sibling that is an HTMLElement
772 * @method getPreviousSibling
773 * @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point
774 * @return {Object} HTMLElement or null if not found
776 getPreviousSibling: function(node) {
777 node = Y.Dom.get(node);
782 return Y.Dom.getPreviousSiblingBy(node);
786 * Returns the next HTMLElement sibling that passes the boolean method.
787 * For performance reasons, IDs are not accepted and argument validation omitted.
788 * Returns the nearest HTMLElement sibling if no method provided.
789 * @method getNextSiblingBy
790 * @param {HTMLElement} node The HTMLElement to use as the starting point
791 * @param {Function} method A boolean function used to test siblings
792 * that receives the sibling node being tested as its only argument
793 * @return {Object} HTMLElement or null if not found
795 getNextSiblingBy: function(node, method) {
797 node = node.nextSibling;
798 if ( testElement(node, method) ) {
806 * Returns the next sibling that is an HTMLElement
807 * @method getNextSibling
808 * @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point
809 * @return {Object} HTMLElement or null if not found
811 getNextSibling: function(node) {
812 node = Y.Dom.get(node);
817 return Y.Dom.getNextSiblingBy(node);
821 * Returns the first HTMLElement child that passes the test method.
822 * @method getFirstChildBy
823 * @param {HTMLElement} node The HTMLElement to use as the starting point
824 * @param {Function} method A boolean function used to test children
825 * that receives the node being tested as its only argument
826 * @return {Object} HTMLElement or null if not found
828 getFirstChildBy: function(node, method) {
829 var child = ( testElement(node.firstChild, method) ) ? node.firstChild : null;
830 return child || Y.Dom.getNextSiblingBy(node.firstChild, method);
834 * Returns the first HTMLElement child.
835 * @method getFirstChild
836 * @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point
837 * @return {Object} HTMLElement or null if not found
839 getFirstChild: function(node, method) {
840 node = Y.Dom.get(node);
844 return Y.Dom.getFirstChildBy(node);
848 * Returns the last HTMLElement child that passes the test method.
849 * @method getLastChildBy
850 * @param {HTMLElement} node The HTMLElement to use as the starting point
851 * @param {Function} method A boolean function used to test children
852 * that receives the node being tested as its only argument
853 * @return {Object} HTMLElement or null if not found
855 getLastChildBy: function(node, method) {
859 var child = ( testElement(node.lastChild, method) ) ? node.lastChild : null;
860 return child || Y.Dom.getPreviousSiblingBy(node.lastChild, method);
864 * Returns the last HTMLElement child.
865 * @method getLastChild
866 * @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point
867 * @return {Object} HTMLElement or null if not found
869 getLastChild: function(node) {
870 node = Y.Dom.get(node);
871 return Y.Dom.getLastChildBy(node);
875 * Returns an array of HTMLElement childNodes that pass the test method.
876 * @method getChildrenBy
877 * @param {HTMLElement} node The HTMLElement to start from
878 * @param {Function} method A boolean function used to test children
879 * that receives the node being tested as its only argument
880 * @return {Array} A static array of HTMLElements
882 getChildrenBy: function(node, method) {
883 var child = Y.Dom.getFirstChildBy(node, method);
884 var children = child ? [child] : [];
886 Y.Dom.getNextSiblingBy(child, function(node) {
887 if ( !method || method(node) ) {
888 children[children.length] = node;
890 return false; // fail test to collect all children
897 * Returns an array of HTMLElement childNodes.
898 * @method getChildren
899 * @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point
900 * @return {Array} A static array of HTMLElements
902 getChildren: function(node) {
903 node = Y.Dom.get(node);
907 return Y.Dom.getChildrenBy(node);
911 * Returns the left scroll value of the document
912 * @method getDocumentScrollLeft
913 * @param {HTMLDocument} document (optional) The document to get the scroll value of
914 * @return {Int} The amount that the document is scrolled to the left
916 getDocumentScrollLeft: function(doc) {
917 doc = doc || document;
918 return Math.max(doc.documentElement.scrollLeft, doc.body.scrollLeft);
922 * Returns the top scroll value of the document
923 * @method getDocumentScrollTop
924 * @param {HTMLDocument} document (optional) The document to get the scroll value of
925 * @return {Int} The amount that the document is scrolled to the top
927 getDocumentScrollTop: function(doc) {
928 doc = doc || document;
929 return Math.max(doc.documentElement.scrollTop, doc.body.scrollTop);
933 * Inserts the new node as the previous sibling of the reference node
934 * @method insertBefore
935 * @param {String | HTMLElement} newNode The node to be inserted
936 * @param {String | HTMLElement} referenceNode The node to insert the new node before
937 * @return {HTMLElement} The node that was inserted (or null if insert fails)
939 insertBefore: function(newNode, referenceNode) {
940 newNode = Y.Dom.get(newNode);
941 referenceNode = Y.Dom.get(referenceNode);
943 if (!newNode || !referenceNode || !referenceNode.parentNode) {
947 return referenceNode.parentNode.insertBefore(newNode, referenceNode);
951 * Inserts the new node as the next sibling of the reference node
952 * @method insertAfter
953 * @param {String | HTMLElement} newNode The node to be inserted
954 * @param {String | HTMLElement} referenceNode The node to insert the new node after
955 * @return {HTMLElement} The node that was inserted (or null if insert fails)
957 insertAfter: function(newNode, referenceNode) {
958 newNode = Y.Dom.get(newNode);
959 referenceNode = Y.Dom.get(referenceNode);
961 if (!newNode || !referenceNode || !referenceNode.parentNode) {
965 if (referenceNode.nextSibling) {
966 return referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
968 return referenceNode.parentNode.appendChild(newNode);
973 * Creates a Region based on the viewport relative to the document.
974 * @method getClientRegion
975 * @return {Region} A Region object representing the viewport which accounts for document scroll
977 getClientRegion: function() {
978 var t = Y.Dom.getDocumentScrollTop(),
979 l = Y.Dom.getDocumentScrollLeft(),
980 r = Y.Dom.getViewportWidth() + l,
981 b = Y.Dom.getViewportHeight() + t;
983 return new Y.Region(t, r, b, l);
987 var getXY = function() {
988 if (document.documentElement.getBoundingClientRect) { // IE
989 return function(el) {
990 var box = el.getBoundingClientRect();
992 var rootNode = el.ownerDocument;
993 return [box.left + Y.Dom.getDocumentScrollLeft(rootNode), box.top +
994 Y.Dom.getDocumentScrollTop(rootNode)];
997 return function(el) { // manually calculate by crawling up offsetParents
998 var pos = [el.offsetLeft, el.offsetTop];
999 var parentNode = el.offsetParent;
1001 // safari: subtract body offsets if el is abs (or any offsetParent), unless body is offsetParent
1002 var accountForBody = (isSafari &&
1003 Y.Dom.getStyle(el, 'position') == 'absolute' &&
1004 el.offsetParent == el.ownerDocument.body);
1006 if (parentNode != el) {
1007 while (parentNode) {
1008 pos[0] += parentNode.offsetLeft;
1009 pos[1] += parentNode.offsetTop;
1010 if (!accountForBody && isSafari &&
1011 Y.Dom.getStyle(parentNode,'position') == 'absolute' ) {
1012 accountForBody = true;
1014 parentNode = parentNode.offsetParent;
1018 if (accountForBody) { //safari doubles in this case
1019 pos[0] -= el.ownerDocument.body.offsetLeft;
1020 pos[1] -= el.ownerDocument.body.offsetTop;
1022 parentNode = el.parentNode;
1024 // account for any scrolled ancestors
1025 while ( parentNode.tagName && !patterns.ROOT_TAG.test(parentNode.tagName) )
1027 if (parentNode.scrollTop || parentNode.scrollLeft) {
1028 // work around opera inline/table scrollLeft/Top bug (false reports offset as scroll)
1029 if (!patterns.OP_SCROLL.test(Y.Dom.getStyle(parentNode, 'display'))) {
1030 if (!isOpera || Y.Dom.getStyle(parentNode, 'overflow') !== 'visible') { // opera inline-block misreports when visible
1031 pos[0] -= parentNode.scrollLeft;
1032 pos[1] -= parentNode.scrollTop;
1037 parentNode = parentNode.parentNode;
1043 }() // NOTE: Executing for loadtime branching
1046 * A region is a representation of an object on a grid. It is defined
1047 * by the top, right, bottom, left extents, so is rectangular by default. If
1048 * other shapes are required, this class could be extended to support it.
1049 * @namespace YAHOO.util
1051 * @param {Int} t the top extent
1052 * @param {Int} r the right extent
1053 * @param {Int} b the bottom extent
1054 * @param {Int} l the left extent
1057 YAHOO.util.Region = function(t, r, b, l) {
1060 * The region's top extent
1067 * The region's top extent as index, for symmetry with set/getXY
1074 * The region's right extent
1081 * The region's bottom extent
1088 * The region's left extent
1095 * The region's left extent as index, for symmetry with set/getXY
1103 * Returns true if this region contains the region passed in
1105 * @param {Region} region The region to evaluate
1106 * @return {Boolean} True if the region is contained with this region,
1109 YAHOO.util.Region.prototype.contains = function(region) {
1110 return ( region.left >= this.left &&
1111 region.right <= this.right &&
1112 region.top >= this.top &&
1113 region.bottom <= this.bottom );
1118 * Returns the area of the region
1120 * @return {Int} the region's area
1122 YAHOO.util.Region.prototype.getArea = function() {
1123 return ( (this.bottom - this.top) * (this.right - this.left) );
1127 * Returns the region where the passed in region overlaps with this one
1129 * @param {Region} region The region that intersects
1130 * @return {Region} The overlap region, or null if there is no overlap
1132 YAHOO.util.Region.prototype.intersect = function(region) {
1133 var t = Math.max( this.top, region.top );
1134 var r = Math.min( this.right, region.right );
1135 var b = Math.min( this.bottom, region.bottom );
1136 var l = Math.max( this.left, region.left );
1138 if (b >= t && r >= l) {
1139 return new YAHOO.util.Region(t, r, b, l);
1146 * Returns the region representing the smallest region that can contain both
1147 * the passed in region and this region.
1149 * @param {Region} region The region that to create the union with
1150 * @return {Region} The union region
1152 YAHOO.util.Region.prototype.union = function(region) {
1153 var t = Math.min( this.top, region.top );
1154 var r = Math.max( this.right, region.right );
1155 var b = Math.max( this.bottom, region.bottom );
1156 var l = Math.min( this.left, region.left );
1158 return new YAHOO.util.Region(t, r, b, l);
1164 * @return string the region properties
1166 YAHOO.util.Region.prototype.toString = function() {
1167 return ( "Region {" +
1168 "top: " + this.top +
1169 ", right: " + this.right +
1170 ", bottom: " + this.bottom +
1171 ", left: " + this.left +
1176 * Returns a region that is occupied by the DOM element
1178 * @param {HTMLElement} el The element
1179 * @return {Region} The region that the element occupies
1182 YAHOO.util.Region.getRegion = function(el) {
1183 var p = YAHOO.util.Dom.getXY(el);
1186 var r = p[0] + el.offsetWidth;
1187 var b = p[1] + el.offsetHeight;
1190 return new YAHOO.util.Region(t, r, b, l);
1193 /////////////////////////////////////////////////////////////////////////////
1197 * A point is a region that is special in that it represents a single point on
1199 * @namespace YAHOO.util
1201 * @param {Int} x The X position of the point
1202 * @param {Int} y The Y position of the point
1204 * @extends YAHOO.util.Region
1206 YAHOO.util.Point = function(x, y) {
1207 if (YAHOO.lang.isArray(x)) { // accept input from Dom.getXY, Event.getXY, etc.
1208 y = x[1]; // dont blow away x yet
1213 * The X position of the point, which is also the right, left and index zero (for Dom.getXY symmetry)
1218 this.x = this.right = this.left = this[0] = x;
1221 * The Y position of the point, which is also the top, bottom and index one (for Dom.getXY symmetry)
1225 this.y = this.top = this.bottom = this[1] = y;
1228 YAHOO.util.Point.prototype = new YAHOO.util.Region();
1230 YAHOO.register("dom", YAHOO.util.Dom, {version: "2.5.2", build: "1076"});