Section A. The style property


A. The style property

The first, and best-known, way of modifying CSS is through the style property that all HTML elements possess, and that accesses their inline styles. style contains one property for every inline CSS declaration. If you want to set an element's CSS margin, you use element.style.margin. If you want to set its CSS color, you use element.style.color. The JavaScript property always has a name similar to the CSS property.

Inline Styles!

Remember: the style property of an HTML element gives access to the inline styles of that element.


Let's review a bit of CSS theory. CSS offers four ways to define styles on an element. You can use inline styles, where you put your CSS directly in the style attribute of the HTML tag:

<p style="margin: 10%">Text</p> 


In addition, you can embed, link to, or import a style sheet. However, since an inline style is more specific than any other kind of style, inline styles overrule styles defined in an embedded, linked, or imported style sheet. Because the style property gives access to these inline styles, it will always overrule all other styles. That's the great strength of this method.

However, when you try to read out styles, you might encounter problems. Take this example:

<p >Text</p> p#test {    margin: 10%; } alert(document.getElementById('test').style.margin); 


The test paragraph doesn't have any inline styles. Instead, the margin: 10% is defined in an embedded (or linked or imported) style sheet, and is therefore impossible to read through the style property. The alert remains empty.

In the next example, the alert will return a result of "10%", because margin has now been defined as an inline style:

<p style="margin: 10%" >Text</p> alert(document.getElementById('test').style.margin); 


Thus, the style property is excellently suited for setting styles, but less useful for getting them. Later we'll discuss ways to get styles from an embedded, linked, or imported style sheet.

Dashes

Many CSS property names contain a dash, for instance font-size. In JavaScript, however, a dash means "minus," and therefore it cannot be used in a property name. This gives an error:

   element.style.font-size = '120%'; 


Does the browser have to subtract the (undefined) variable size from element.style.font? If so, what does the = '120%' bit mean? Instead, the browser expects a camelCase property name:

element.style.fontSize = '120%'; 


The general rule is that all dashes are removed from the CSS property names, and that the character after a dash becomes uppercase. Thus margin-left becomes marginLeft, text-decoration becomes textDecoration, and border-left-style becomes borderLeftStyle.

Units

Many numerical values in JavaScript need a unit, just as they do in CSS. What does fontSize=120 mean? 120 pixels? 120 points? 120 percent? The browser doesn't know, and therefore it doesn't do anything. The unit is necessary to clarify your intent.

Take the setWidth() function, which forms the core of the animations in XMLHTTP Speed Meter:

[XMLHTTP Speed Meter, lines 70-73]

function setWidth(width) {    if (width < 0) width = 0;    document.getElementById('meter').style.width = width + 'px'; } 


The function is handed a value, and it should change the width of the meter to this new value. After a safety check that allows only 0 or larger numbers, it sets the style.width of the element to the new width. Then it adds + 'px', because without that, the browsers wouldn't know how to interpret the number, and would do nothing.

Don't Forget Your 'PX'

Forgetting to append the 'px' unit to a width or height is a common CSS modification error.

In CSS quirks mode, adding 'px' is not necessary, since the browsers obey the old rule that a unitless number is a pixel value. In itself this is not a problem, but many Web developers have acquired the habit of leaving out units when they change widths or heights, and encounter problems when they work in CSS strict mode.


Getting styles

Warning

Browser incompatibilities ahead


As we saw, the style property cannot read out styles set in embedded, linked, or imported style sheets. Because Web developers occasionally need to read out these styles nonetheless, both Microsoft and W3C have created ways of accessing non-inline styles. The Microsoft solution works only in Explorer, while the W3C standard works in Mozilla and Opera.

Microsoft's solution is the currentStyle property, which works exactly like the style property, except for two things:

  • It has access to all styles, not just the inline ones, and therefore reports the style that is actually applied to the element.

  • It is read-only; you cannot set it.

For instance:

var x = document.getElementById('test'); alert(x.currentStyle.color); 


Now the alert shows the current color style of the element, regardless of where it's defined.

W3C's solution is the window.getComputedStyle() method, which works similarly but with a more complicated syntax:

var x = document.getElementById('test'); alert(window.getComputedStyle(x,null).color); 


getComputedStyle() always returns a pixel value, even if the original style was, for instance, 50em or 11%.

As always when we encounter incompatibilities, we need a bit of code branching to satisfy all browsers:

function getRealStyle(id,styleName) {     var element = document.getElementById(id);     var realStyle = null;     if (element.currentStyle)            realStyle = element.currentStyle[styleName];     else if (window.getComputedStyle)            realStyle = window.getComputedStyle(element,null)[styleName];     return realStyle; } 


You use this function as follows:

var textDecStyle = getRealStyle('test','textDecoration'); 


Remember that getComputedStyle() will always return a pixel value, while currentStyle retains the unit specified in the CSS.

Shorthand styles

Warning

Browser incompatibilities ahead


Whether you get inline styles through the style property, or other styles through the function we just discussed, you'll encounter problems when you try to read out shorthand styles.

Take this border declaration:

<p  style="border: 1px solid #cc0000;">Text</p> 


Since this is an inline style, you'd expect this line of code to work:

alert(document.getElementById('test').style.border);  


Unfortunately, it doesn't. The browsers disagree on the exact value they show in the alert.

  • Explorer 6.0 gives #cc0000 1px solid.

  • Mozilla 1.7.12 gives 1px solid rgb(204,0,0).

  • Opera 9 gives 1px solid #cc0000.

  • Safari 1.3 doesn't give any border value.

The problem is that border is a shorthand declaration. It secretly consists of no less than twelve styles: width, style, and color for the top, left, bottom, and right borders. Similarly, the font declaration is shorthand for font-size, font-family, font-weight, and line-height, so it exhibits similar problems.

RGB()

Note the special color syntax Mozilla uses: rgb(204,0,0). This is a valid alternative to the traditional #cc0000; and you can use either syntax in CSS and JavaScript.


How is the browser supposed to handle such shorthand declarations? The example above seems pretty straightforward; you would intuitively expect the browser to return 1px solid #cc0000, exactly as the inline style attribute says. Unfortunately, shorthand properties are more complicated than that.

Consider the following case:

p {     border: 1px solid #cc0000; } <p  style="border-color: #00cc00;">Test</p> alert(document.getElementById('test').style.borderRightColor); 


All browsers report the correct color, even though the inline style doesn't contain a border-right-color but a border-color declaration. Apparently the browsers consider the color of the right border to be set when the color of the entire border is set; not an unreasonable line of thought.

As you see, browsers have to make rules for these unusual situations, and they have chosen slightly different approaches to handle shorthand declarations. In the absence of a specification for the exact handling of shorthand properties, it's impossible to say which browsers are right or wrong.



ppk on JavaScript. Modern, Accessible, Unobtrusive JavaScript Explained by Means of Eight Real-World Example Scripts2006
ppk on JavaScript. Modern, Accessible, Unobtrusive JavaScript Explained by Means of Eight Real-World Example Scripts2006
ISBN: N/A
EAN: N/A
Year: 2005
Pages: 116

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net