Upgrade to ExtJS 3.0.3 - Released 10/11/2009
[extjs.git] / src / core / core / Element.style.js
1 /*!
2  * Ext JS Library 3.0.3
3  * Copyright(c) 2006-2009 Ext JS, LLC
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 /**
8  * @class Ext.Element
9  */
10 Ext.Element.addMethods(function(){  
11     // local style camelizing for speed
12     var propCache = {},
13         camelRe = /(-[a-z])/gi,
14         classReCache = {},
15         view = document.defaultView,
16         propFloat = Ext.isIE ? 'styleFloat' : 'cssFloat',
17         opacityRe = /alpha\(opacity=(.*)\)/i,
18         trimRe = /^\s+|\s+$/g,
19         EL = Ext.Element,   
20         PADDING = "padding",
21         MARGIN = "margin",
22         BORDER = "border",
23         LEFT = "-left",
24         RIGHT = "-right",
25         TOP = "-top",
26         BOTTOM = "-bottom",
27         WIDTH = "-width",    
28         MATH = Math,
29         HIDDEN = 'hidden',
30         ISCLIPPED = 'isClipped',
31         OVERFLOW = 'overflow',
32         OVERFLOWX = 'overflow-x',
33         OVERFLOWY = 'overflow-y',
34         ORIGINALCLIP = 'originalClip',
35         // special markup used throughout Ext when box wrapping elements    
36         borders = {l: BORDER + LEFT + WIDTH, r: BORDER + RIGHT + WIDTH, t: BORDER + TOP + WIDTH, b: BORDER + BOTTOM + WIDTH},
37         paddings = {l: PADDING + LEFT, r: PADDING + RIGHT, t: PADDING + TOP, b: PADDING + BOTTOM},
38         margins = {l: MARGIN + LEFT, r: MARGIN + RIGHT, t: MARGIN + TOP, b: MARGIN + BOTTOM},
39         data = Ext.Element.data;
40         
41     
42     // private  
43     function camelFn(m, a) {
44         return a.charAt(1).toUpperCase();
45     }
46     
47     function chkCache(prop) {
48         return propCache[prop] || (propCache[prop] = prop == 'float' ? propFloat : prop.replace(camelRe, camelFn));
49     }
50             
51     return {
52         // private  ==> used by Fx  
53         adjustWidth : function(width) {
54             var me = this;
55             var isNum = Ext.isNumber(width);
56             if(isNum && me.autoBoxAdjust && !me.isBorderBox()){
57                width -= (me.getBorderWidth("lr") + me.getPadding("lr"));
58             }
59             return (isNum && width < 0) ? 0 : width;
60         },
61         
62         // private   ==> used by Fx 
63         adjustHeight : function(height) {
64             var me = this;
65             var isNum = Ext.isNumber(height);
66             if(isNum && me.autoBoxAdjust && !me.isBorderBox()){
67                height -= (me.getBorderWidth("tb") + me.getPadding("tb"));               
68             }
69             return (isNum && height < 0) ? 0 : height;
70         },
71     
72     
73         /**
74          * Adds one or more CSS classes to the element. Duplicate classes are automatically filtered out.
75          * @param {String/Array} className The CSS class to add, or an array of classes
76          * @return {Ext.Element} this
77          */
78         addClass : function(className){
79             var me = this;
80             Ext.each(className, function(v) {
81                 me.dom.className += (!me.hasClass(v) && v ? " " + v : "");  
82             });
83             return me;
84         },
85     
86         /**
87          * Adds one or more CSS classes to this element and removes the same class(es) from all siblings.
88          * @param {String/Array} className The CSS class to add, or an array of classes
89          * @return {Ext.Element} this
90          */
91         radioClass : function(className){
92             Ext.each(this.dom.parentNode.childNodes, function(v) {
93                 if(v.nodeType == 1) {
94                     Ext.fly(v, '_internal').removeClass(className);          
95                 }
96             });
97             return this.addClass(className);
98         },
99     
100         /**
101          * Removes one or more CSS classes from the element.
102          * @param {String/Array} className The CSS class to remove, or an array of classes
103          * @return {Ext.Element} this
104          */
105         removeClass : function(className){
106             var me = this;
107             if (me.dom && me.dom.className) {
108                 Ext.each(className, function(v) {               
109                     me.dom.className = me.dom.className.replace(
110                         classReCache[v] = classReCache[v] || new RegExp('(?:^|\\s+)' + v + '(?:\\s+|$)', "g"), 
111                         " ");               
112                 });    
113             }
114             return me;
115         },
116     
117         /**
118          * Toggles the specified CSS class on this element (removes it if it already exists, otherwise adds it).
119          * @param {String} className The CSS class to toggle
120          * @return {Ext.Element} this
121          */
122         toggleClass : function(className){
123             return this.hasClass(className) ? this.removeClass(className) : this.addClass(className);
124         },
125     
126         /**
127          * Checks if the specified CSS class exists on this element's DOM node.
128          * @param {String} className The CSS class to check for
129          * @return {Boolean} True if the class exists, else false
130          */
131         hasClass : function(className){
132             return className && (' '+this.dom.className+' ').indexOf(' '+className+' ') != -1;
133         },
134     
135         /**
136          * Replaces a CSS class on the element with another.  If the old name does not exist, the new name will simply be added.
137          * @param {String} oldClassName The CSS class to replace
138          * @param {String} newClassName The replacement CSS class
139          * @return {Ext.Element} this
140          */
141         replaceClass : function(oldClassName, newClassName){
142             return this.removeClass(oldClassName).addClass(newClassName);
143         },
144         
145         isStyle : function(style, val) {
146             return this.getStyle(style) == val;  
147         },
148     
149         /**
150          * Normalizes currentStyle and computedStyle.
151          * @param {String} property The style property whose value is returned.
152          * @return {String} The current value of the style property for this element.
153          */
154         getStyle : function(){         
155             return view && view.getComputedStyle ?
156                 function(prop){
157                     var el = this.dom,
158                         v,                  
159                         cs,
160                         out;
161                     if(el == document) return null;
162                     prop = chkCache(prop);
163                     out = (v = el.style[prop]) ? v : 
164                            (cs = view.getComputedStyle(el, "")) ? cs[prop] : null;
165                     
166                     // Webkit returns rgb values for transparent.
167                     if(Ext.isWebKit && out == 'rgba(0, 0, 0, 0)'){
168                         out = 'transparent';
169                     }
170                     return out;
171                 } :
172                 function(prop){      
173                     var el = this.dom, 
174                         m, 
175                         cs;     
176                         
177                     if(el == document) return null;      
178                     if (prop == 'opacity') {
179                         if (el.style.filter.match) {                       
180                             if(m = el.style.filter.match(opacityRe)){
181                                 var fv = parseFloat(m[1]);
182                                 if(!isNaN(fv)){
183                                     return fv ? fv / 100 : 0;
184                                 }
185                             }
186                         }
187                         return 1;
188                     }
189                     prop = chkCache(prop);  
190                     return el.style[prop] || ((cs = el.currentStyle) ? cs[prop] : null);
191                 };
192         }(),
193
194         /**
195          * Return the CSS color for the specified CSS attribute. rgb, 3 digit (like #fff) and valid values
196          * are convert to standard 6 digit hex color.
197          * @param {String} attr The css attribute
198          * @param {String} defaultValue The default value to use when a valid color isn't found
199          * @param {String} prefix (optional) defaults to #. Use an empty string when working with
200          * color anims.
201          */
202         getColor : function(attr, defaultValue, prefix){
203             var v = this.getStyle(attr),
204                 color = Ext.isDefined(prefix) ? prefix : '#',
205                 h;
206                 
207             if(!v || /transparent|inherit/.test(v)){
208                 return defaultValue;
209             }
210             if(/^r/.test(v)){
211                 Ext.each(v.slice(4, v.length -1).split(','), function(s){
212                     h = parseInt(s, 10);
213                     color += (h < 16 ? '0' : '') + h.toString(16); 
214                 });
215             }else{
216                 v = v.replace('#', '');
217                 color += v.length == 3 ? v.replace(/^(\w)(\w)(\w)$/, '$1$1$2$2$3$3') : v;
218             }
219             return(color.length > 5 ? color.toLowerCase() : defaultValue);
220         },
221     
222         /**
223          * Wrapper for setting style properties, also takes single object parameter of multiple styles.
224          * @param {String/Object} property The style property to be set, or an object of multiple styles.
225          * @param {String} value (optional) The value to apply to the given property, or null if an object was passed.
226          * @return {Ext.Element} this
227          */
228         setStyle : function(prop, value){
229             var tmp, 
230                 style,
231                 camel;
232             if (!Ext.isObject(prop)) {
233                 tmp = {};
234                 tmp[prop] = value;          
235                 prop = tmp;
236             }
237             for (style in prop) {
238                 value = prop[style];            
239                 style == 'opacity' ? 
240                     this.setOpacity(value) : 
241                     this.dom.style[chkCache(style)] = value;
242             }
243             return this;
244         },
245         
246         /**
247          * Set the opacity of the element
248          * @param {Float} opacity The new opacity. 0 = transparent, .5 = 50% visibile, 1 = fully visible, etc
249          * @param {Boolean/Object} animate (optional) a standard Element animation config object or <tt>true</tt> for
250          * the default animation (<tt>{duration: .35, easing: 'easeIn'}</tt>)
251          * @return {Ext.Element} this
252          */
253          setOpacity : function(opacity, animate){
254             var me = this,
255                 s = me.dom.style;
256                 
257             if(!animate || !me.anim){            
258                 if(Ext.isIE){
259                     var opac = opacity < 1 ? 'alpha(opacity=' + opacity * 100 + ')' : '', 
260                     val = s.filter.replace(opacityRe, '').replace(trimRe, '');
261
262                     s.zoom = 1;
263                     s.filter = val + (val.length > 0 ? ' ' : '') + opac;
264                 }else{
265                     s.opacity = opacity;
266                 }
267             }else{
268                 me.anim({opacity: {to: opacity}}, me.preanim(arguments, 1), null, .35, 'easeIn');
269             }
270             return me;
271         },
272         
273         /**
274          * Clears any opacity settings from this element. Required in some cases for IE.
275          * @return {Ext.Element} this
276          */
277         clearOpacity : function(){
278             var style = this.dom.style;
279             if(Ext.isIE){
280                 if(!Ext.isEmpty(style.filter)){
281                     style.filter = style.filter.replace(opacityRe, '').replace(trimRe, '');
282                 }
283             }else{
284                 style.opacity = style['-moz-opacity'] = style['-khtml-opacity'] = '';
285             }
286             return this;
287         },
288     
289         /**
290          * Returns the offset height of the element
291          * @param {Boolean} contentHeight (optional) true to get the height minus borders and padding
292          * @return {Number} The element's height
293          */
294         getHeight : function(contentHeight){
295             var me = this,
296                 dom = me.dom,
297                 hidden = Ext.isIE && me.isStyle('display', 'none'),
298                 h = MATH.max(dom.offsetHeight, hidden ? 0 : dom.clientHeight) || 0;
299                 
300             h = !contentHeight ? h : h - me.getBorderWidth("tb") - me.getPadding("tb");
301             return h < 0 ? 0 : h;
302         },
303     
304         /**
305          * Returns the offset width of the element
306          * @param {Boolean} contentWidth (optional) true to get the width minus borders and padding
307          * @return {Number} The element's width
308          */
309         getWidth : function(contentWidth){
310             var me = this,
311                 dom = me.dom,
312                 hidden = Ext.isIE && me.isStyle('display', 'none'),
313                 w = MATH.max(dom.offsetWidth, hidden ? 0 : dom.clientWidth) || 0;
314             w = !contentWidth ? w : w - me.getBorderWidth("lr") - me.getPadding("lr");
315             return w < 0 ? 0 : w;
316         },
317     
318         /**
319          * Set the width of this Element.
320          * @param {Mixed} width The new width. This may be one of:<div class="mdetail-params"><ul>
321          * <li>A Number specifying the new width in this Element's {@link #defaultUnit}s (by default, pixels).</li>
322          * <li>A String used to set the CSS width style. Animation may <b>not</b> be used.
323          * </ul></div>
324          * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
325          * @return {Ext.Element} this
326          */
327         setWidth : function(width, animate){
328             var me = this;
329             width = me.adjustWidth(width);
330             !animate || !me.anim ? 
331                 me.dom.style.width = me.addUnits(width) :
332                 me.anim({width : {to : width}}, me.preanim(arguments, 1));
333             return me;
334         },
335     
336         /**
337          * Set the height of this Element.
338          * <pre><code>
339 // change the height to 200px and animate with default configuration
340 Ext.fly('elementId').setHeight(200, true);
341
342 // change the height to 150px and animate with a custom configuration
343 Ext.fly('elId').setHeight(150, {
344     duration : .5, // animation will have a duration of .5 seconds
345     // will change the content to "finished"
346     callback: function(){ this.{@link #update}("finished"); } 
347 });
348          * </code></pre>
349          * @param {Mixed} height The new height. This may be one of:<div class="mdetail-params"><ul>
350          * <li>A Number specifying the new height in this Element's {@link #defaultUnit}s (by default, pixels.)</li>
351          * <li>A String used to set the CSS height style. Animation may <b>not</b> be used.</li>
352          * </ul></div>
353          * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
354          * @return {Ext.Element} this
355          */
356          setHeight : function(height, animate){
357             var me = this;
358             height = me.adjustHeight(height);
359             !animate || !me.anim ? 
360                 me.dom.style.height = me.addUnits(height) :
361                 me.anim({height : {to : height}}, me.preanim(arguments, 1));
362             return me;
363         },
364         
365         /**
366          * Gets the width of the border(s) for the specified side(s)
367          * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
368          * passing <tt>'lr'</tt> would get the border <b><u>l</u></b>eft width + the border <b><u>r</u></b>ight width.
369          * @return {Number} The width of the sides passed added together
370          */
371         getBorderWidth : function(side){
372             return this.addStyles(side, borders);
373         },
374     
375         /**
376          * Gets the width of the padding(s) for the specified side(s)
377          * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
378          * passing <tt>'lr'</tt> would get the padding <b><u>l</u></b>eft + the padding <b><u>r</u></b>ight.
379          * @return {Number} The padding of the sides passed added together
380          */
381         getPadding : function(side){
382             return this.addStyles(side, paddings);
383         },
384     
385         /**
386          *  Store the current overflow setting and clip overflow on the element - use <tt>{@link #unclip}</tt> to remove
387          * @return {Ext.Element} this
388          */
389         clip : function(){
390             var me = this,
391                 dom = me.dom;
392                 
393             if(!data(dom, ISCLIPPED)){
394                 data(dom, ISCLIPPED, true);
395                 data(dom, ORIGINALCLIP, {
396                     o: me.getStyle(OVERFLOW),
397                     x: me.getStyle(OVERFLOWX),
398                     y: me.getStyle(OVERFLOWY)
399                 });
400                 me.setStyle(OVERFLOW, HIDDEN);
401                 me.setStyle(OVERFLOWX, HIDDEN);
402                 me.setStyle(OVERFLOWY, HIDDEN);
403             }
404             return me;
405         },
406     
407         /**
408          *  Return clipping (overflow) to original clipping before <tt>{@link #clip}</tt> was called
409          * @return {Ext.Element} this
410          */
411         unclip : function(){
412             var me = this,
413                 dom = me.dom;
414                 
415             if(data(dom, ISCLIPPED)){
416                 data(dom, ISCLIPPED, false);
417                 var o = data(dom, ORIGINALCLIP);
418                 if(o.o){
419                     me.setStyle(OVERFLOW, o.o);
420                 }
421                 if(o.x){
422                     me.setStyle(OVERFLOWX, o.x);
423                 }
424                 if(o.y){
425                     me.setStyle(OVERFLOWY, o.y);
426                 }
427             }
428             return me;
429         },
430
431         // private
432         addStyles : function(sides, styles){
433             var val = 0;
434
435             Ext.each(sides.match(/\w/g), function(s) {
436                 if (s = parseInt(this.getStyle(styles[s]), 10)) {
437                     val += MATH.abs(s);
438                 }
439             },
440             this);
441             return val;
442         },
443
444         margins : margins
445     }
446 }()         
447 );