Section 12.1. DHTML: JavaScript, CSS, and DOM


12.1. DHTML: JavaScript, CSS, and DOM

Cascading Style Sheets (CSS) had a rough start. The idea of putting the presentation of page elements into a separate specification was around before the beginnings of the Web, but was pushed aside by earliest browser developers. It wasn't until 1996with the first release of CSS, followed by the first releases of the 4.x browsersthat CSS finally became a reality. None too soon, because web-page developers were getting quite frustrated with web-page limitations.

In those early days, most pages were laid out using HTML tables, which originally were not intended for page layout, but data organization. Problems associated with page layout included the entire page not displaying until all images were loaded, not to mention all of the cruft that was creeping into page development through the different browsers. If you worked with web pages then, you're familiar with font and, worse, blink.

CSS provided a clean alternative; with it, you could initialize and manipulate different categories of presentation properties. These include an element's background, font, colors, borders, and box size, margins, and padding, if applicable. These were a very nice addition to a web-application developer's toolbox, but there was something missing: the ability to position elements and control their layout, as well as their visibility and display. It wasn't until Netscape and Microsoft collaborated on an early release of positional CSS, called CSS-P, that these style properties were released. Eventually, they were rolled into a new release of CSS: CSS2.

This chapter assumes you're familiar with CSS and how to add stylesheets to a web page. If you're unfamiliar with CSS, you may want to read a good tutorial or book on CSS first before reading the rest of this chapter. I recommend Eric A. Meyer's Cascading Style Sheets: The Definitive Guide (O'Reilly). There are also numerous tutorials online if you do a search on "CSS" and "tutorial." One popular site is W3 Schools at http://www.w3schools.com/css/default.asp.


12.1.1. The style Property

CSS style properties are typically retrieved and set via the style object. The concept of style as property originated with Microsoft, but was adopted by the W3C and included in the DOM Level 2 CSS module. Through the W3C DOM, any node has an associated style object as a property, which means any page element can have its style properties changed with JavaScript.

To change any style setting using JavaScript, you must first use one of the DOM-access methods outlined in Chapters 9 and 10 to get a handle on the individual element (or elements). To change the style attribute, use straight assignment:

element.style.color="#fff";

This works with any valid CSS2 attribute and on any valid XHTML object. Example 12-1 shows how to modify several CSS attributes, using our by now very familiar getElementById to access a DIV element, and the style object to set various CSS properties.

Example 12-1. Applying several style property changes to a DIV element

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Changing Styles</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript"> //<![CDATA[ function changeElement(  ) {   var div = document.getElementById("div1");   div.style.backgroundColor="#f00";   div.style.width="500px";   div.style.color="#fff";   div.style.height="200px";   div.style.paddingLeft="50px";   div.style.paddingTop="50px";   div.style.fontFamily="Verdana";   div.style.borderColor="#000"; } //]]> </script> </head> <body onload="changeElement(  );"> <div > This is a DIV element. </div> </body> </html>

Notice in the example the naming convention used with the CSS properties? If the property has a hyphen, such as border-color, the hyphen is removed and the first letter of the second term is capitalized: border-color in CSS becomes borderColor in JavaScript. Other than that, the names of the CSS properties used in JavaScript are the same as the names of the properties in a stylesheet. Figure 12-1 demonstrates how the DIV element and its contents look after the style changes have been made.

Figure 12-1. Applying several style changes


If modifying the style attribute is simple, reading it is less so. If the style property is not set through JavaScript or using the style attribute inline in the element, even if the value is set with a stylesheet, the property value will either be blank or undefined. This is important to remember because it will trip you up more than anything else when you're working with DHTML. The style settings used to render the object initially are internal to the browser and based on a combination of stylesheet settings, as well as element inheritance.

To repeat: unless the style property is set via JavaScript or directly in-line using the style attribute on the element, the value is blank or undefined when you access it via script, even if you set the value through a stylesheet.


To access the style, you need to use other properties, each specific to different types of browsers. Microsoft and Opera support a currentStyle property on the element, while Firefox, Mozilla, and Navigator support window.getComputedStyle. Unfortunately, these don't work consistently across browsers.

For the getComputedStyle method, you must pass in the CSS attribute using the same syntax you use when setting the style in the stylesheet. However, for the currentStyle method, you use the JavaScript notation. (It doesn't matter either way what you use with Safari, because it doesn't support any method.)

Example 12-2 demonstrates a variation of a function that gets the style settings for an object and a specific CSS property. It tests, first, whether window.getComputedStyle is supported, and if not, tests for getComputedStyle. If neither are supported, it just returns null. The style property is also accessed and printed out, both before and after it's set.

Example 12-2. Attempting to get CSS style information

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Shy Style</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <style type="text/css"> #div1 { background-color: #ff0 } </style> <script type="text/javascript"> //<![CDATA[ document.onclick=changeElement; function getStyle(obj,jsprop,cssprop) {    if (obj.currentStyle) {        return obj.currentStyle[jsprop];    } else if (window.getComputedStyle) {       return document.defaultView.getComputedStyle(obj,null).getPropertyValue(cssprop);    } else {      return null;    } } function changeElement(  ) {     var obj = document.getElementById("div1");     alert(obj.style.backgroundColor);     alert(getStyle(obj,"backgroundColor","background-color"));     obj.style.backgroundColor="#ff0000";     alert(getStyle(obj,"backgroundColor","background-color"));     alert(obj.style.backgroundColor); } //]]> </script> </head> <body> <div > <p>This is a DIV element</p> </div> </body> </html>

Notice in the script that the syntax to get the computed value is document.defaultView.getComputedStyle rather than window.getComputedStyle. The reason is that document.defaultView returns the DOM AbstractView object, which is the base interface from which all views derive. This may be set to the window object, but there's no guarantee, and it could change from browser to browser, or version to version. As such, you'll want to use document.defaultView.getComputedStyle to get the style property.

Even when the style property is accessible, what exactly is returned also varies from browser to browser; for instance color, simple color. Opera returns the hexadecimal format for the color:

#ff0000

While Firefox returns the RGB setting:

RGB(255,0,0)

You then need to convert between the two formats if you want a consistent result.

Retrieving style settings from the page is fraught with interesting challenges. Perhaps more so than is fun, entertaining, or even useful. A good rule of thumb when working with DHTML is try to avoid retrieving information directly from the page style settings. Instead, whenever possible, use program variables to hold values and only use style to set attributes.

The CSS style properties tend to fall into families of like properties: fonts, borders, the container for elements, positioning, display, and so on. In the rest of the chapter, I'll cover several attributes, demonstrating how to work with each using JavaScript. Definitely take some time along the way to stop and improvise on all of the examples.

Getting style information through the document's stylesheet collection is not covered here. This is a newer collection and not part of the original BOM. Using this approach works around some of the compatibility and attribute-setting difficulties discussed in this chapter. To see an example and discussion on this approach, see "Modifying Styles" by Steven Champeon at http://developer.apple.com/internet/webcontent/styles.html.





Learning JavaScript
Learning JavaScript, 2nd Edition
ISBN: 0596521871
EAN: 2147483647
Year: 2006
Pages: 151

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