Chapter 12. Dynamic HTML

CONTENTS

CONTENTS>>

  •  What Is Dynamic HTML?
  •  Cascading Style Sheets
  •  Borders
  •  External CSS Style Sheets
  •  The Role of JavaScript in Dynamic HTML
  •  Summary

What Is Dynamic HTML?

With version 4 of both Internet Explorer and Netscape Navigator came Dynamic HTML (DHTML). At the heart of DHTML is the capacity to move objects dynamically on an HTML page and to use absolute positioning. Actually, absolute positioning and dynamic movement are related because changing one absolute position, or a position relative to an absolute one, to a different position simulates movement. To make DHTML work, something had to be available to trigger or drive the dynamic changes. For the most part, this role has been filled by JavaScript and event handlers.

In addition to the capability to put an object where you want it on a page without using tables or frames in HTML, another feature of DHTML is Cascading Style Sheets (CSS). As demonstrated in examples throughout the book, CSS is a designer's best friend. Not only can all manner of font styles, types, sizes, and weight be controlled, but so can margins, indents, and other structural elements in text.

DHTML started the movement to separate style from content. In other words, HTML tables were never intended to control layout. It is much more ideal to control layout with one external style sheet.

About the same time that DHTML was introduced, programs such as Macromedia Dreamweaver and later Adobe GoLive made creating DHTML sites that much easier, albeit with some code bloat and hitches with cross-browser and cross-platform compatibility. However, the cross-browser incompatibility was not the application's fault; it was the fault of Netscape and Microsoft for not adhering to a common standard developed by the World Wide Web Consortium (W3C) or working out one between themselves. To make a long and sordid story short, the incompatibilities between NN4 and IE4 were so great that developers were faced with creating sites for one browser or the other. Some attempted to write cross-browser scripts, but doing so literally doubled the work of the developer. It was easier to use animated GIFs movement and complex tables for approximating absolute positioning.

It is definitely a complex task to implement custom DHTML cross-browser/ platform programming. If/Else conditional statements, however, make it possible to write functions that will work on varying browsers/platforms.

NOTE

While the nonsense around DHTML was going on unresolved, developers and designers discovered Macromedia Flash. Not only did Flash do what they wanted as far as animation and absolute positioning was concerned, but it also did it at a very low bandwidth and was cross-everything compatible with the necessary plug-in. Then both Microsoft and Netscape decided to embed the plug-in for Flash into their browsers, so the concern about users not having the appropriate plug-in was resolved. Instead of waiting for the two major browser developers to get their acts together with DHTML, many turned to Flash. (See Chapter 18, "Flash ActionScript and JavaScript," for a discussion of JavaScript's relationship to Flash.) With Flash 5 ActionScripting being based on JavaScript, it is becoming much more attractive to approach dynamic projects with Flash.

At the time of this writing, both Netscape Navigator and Internet Explorer were in Version 6 of their respective browsers on Windows platforms, and NN6 and IE5 on the Macintosh. While each still has its own way of positioning the contents of a <DIV> container, some correspondence between the two is apparent in DHTML.

Cascading Style Sheets

One relatively stable feature of DHTML is CSS. In looking at the two browsers and Windows and Macintosh operating systems, you find some differences, but not many. This is especially true with IE6 and NN6. In this section, I want to go over some of the more critical visual elements that are part of CSS. CSS has an aural component that is not addressed in this book, as well as many other features that make CSS an important designer's tool. One highly regarded source is Cascading Style Sheets 2.0 Programmer's Reference, by Eric A. Meyer (Osborne, 2001). Online, you cannot do better than the CSS2 standard, at http://www.w3.org/TR/REC-CSS2/about.html. Here, though, you need to understand something about the basics.

Standard Units of Measurement in CSS

The first feature and one of the nicest of CSS to be discussed is the units of measurement in CSS. Those with a design background, especially page design, are accustomed to working in a world in which measurement is in terms of pica, leading, kerning points, and similar units not available in standard HTML. However, with CSS, many of these familiar units of measurement are once again available for making a page. Table 12.1 shows the units of measurement available in HTML.

Table 12.1. CSS Standard Units of Measurement

Symbol

Meaning

em

Horizontal distance of the letter m relative to the point size of the current font

ex

Vertical height of the letter x relative to the current font

px

1 pixel unit on the computer monitor

in

1 inch

cm

1 centimeter

mm

1 millimeter

pt

1 point (1/72 inch, but actual size depends on monitor screen setting)

pc

1 pica is 12 points

%

Percentage relative to another specified font size

Those without a page design background can find many books on page makeup whose principles of page design readily apply to HTML. Because of both the dynamic character of web pages, especially those with JavaScript, and the differing sizes of screens, you must design for web pages with a slightly different perspective. However, good page design for paper pages developed over the years almost always applies to web pages as well.

More Than Pretty Fonts and Colors

To get started, I want to provide a point of departure and reference. This next script has a little of everything in it and is shown on two different browsers (NN6 and IE6 on Windows) in Figure 12.1.

Figure 12.1. Only slight differences in the borders are noticeable when CSS is used in either NN6 or IE6.

graphics/12fig01.gif

<html>  <head>  <title> CSS Potpourri </title>  <style type="text/css">  body {       cursor:crosshair;        background-color:ba3600;        color:ebde33;        font-weight:bold;  }  .test {       border: groove;        border-color:ab8f03;        border-width:thick;        position:absolute;        left:300px;        top:100px;        text-transform:capitalize; //First letter of each word capitalized        font-family: verdana;        background-color:ff4a00;        color:white;        margin-left:2em;        text-indent:2em;        text-align:center;  }  div {       background-color:ab8f03;        font-variant:small-caps;  }  </style>  </head>  <body>  <div>you know what i need  <span class="test" >  javaScript is just what i need  </span>  <p>And I need it Now</div>  </body>  </html>

Before going further, take a look at Figure 12.2 to see an approximation of what the screen appears like in the different browsers in a Windows environment.

Figure 12.2. Using the <div> tag helps to provide an integrated block of text.

graphics/12fig02.gif

If you look at the tags after the <body> tag in the script, you should notice that all of the text and other tags are within the <div> container this text line:

you know what i need 

followed by

javaScript is just what i need 

and, finally:

And I need it Now 

The first feature that you should notice is that the second line is below the first two. You might have expected the second line to be placed between the first and the third, but it is not because the second line is part of a <span> containing a CSS class definition (.text) that uses absolute positioning. So, even though all three lines of text are contained within the same <div> container, one of the lines is marching to the beat of a different CSS definition and positioning definition.

Look at the text, how it is formatted, the letter case in the script and on the screen, the different colors and their attendant relationship to the <div> or <span> containers, and the border and positioning attributes. The script will familiarize you with a cross-section of CSS. In the rest of the section, you will see how to use the major visual elements of CSS. Also run the script on pre-V6 browsers to see what is formatted and what is not. Version 4 browsers understand some of the CSS and not others.

<span> and <div> Elements

The <span> element is used in HTML with CSS to create an inline style. That is, only the materials within the <span> container are affected, and the rest of the paragraph is not. The <span> container causes no carriage returns or other breaks in the text. The <div> element, though, is a block element that will not flow in a paragraph. The <div> container can be used for absolute positioning of a block of text; within that block, other styles can be introduced using <span>. In the previous example, the <span> inside the <div> container took precedence over the <div> definitions but included them where they did not conflict. The following simple script shows a block of text within a <div> container:

<html>  <head>  <title>Block Text </title>  <style type="text/css">  div {       font-family:verdana;        font-size:10pt;        background:#ddd;        margin:1em;        text-align:center;  }  </style>  </head>  <body>  <div>&nbsp; <br>Wittenstein and Popper were at odds. Popper demanded<br>  empirically tested hypotheses and Wittenstein<br> saw that both the empirical  world and hypotheses <br>about that world were bound to language in such<br> a  way that the empirical world was nothing but talk<br> about an idea of an idea of  an empirical world.<br>&nbsp;</div>  </body>  </html>

You will find creating blocks of text much easier using the <div> container than several <span> containers or user definitions. (You also might note that only three hexadecimal values were used in the background color definition. That's a shortcut discussed further in the upcoming section "More on Colors.") Figure 12.2 shows the formatted output.

Tags and User-Defined Styles

As you have seen in many examples, HTML tags can be redefined to change the text and format characteristics using this format:

tag { attribute : value } 

User-defined styles have two different formats. First, as you have seen, is the dot definition with the following format:

.name { attribute : value } 

Second, you can define an ID style that is similar to a dot definition, except that it is prefaced by a pound (#) sign in the following format:

#name { attribute : value } 

The only difference between the dot-defined style and the ID style, at the time of this writing, is that you apply the former using the class keyword and the latter using the ID keyword. In future developments of CSS, IDs are supposed to be unique (used only once on a page), and class can be used as many times as needed.

As has been seen in previous examples, the class keyword is used to select a given user-defined style. For example, if a dot-defined style were .hiLite, the class style selection would be this:

<p class=hiLite>...</p> 

A selector defined by an ID (#) such as #loLite is applied using the ID keyword in the tag where it is applied, as the following shows:

<p ID=loLite>....</p> 

The following script shows all three at work:

<html>  <head>  <title>ID and Class Text </title>  <style type="text/css">  body {       font-family:verdana;        font-size:10pt;        }  .hiLite {       background-color:yellow;        color:blue;        font-weight:bold;        }  #loLite {       background-color:blue;        color:yellow;        font-weight:bold;        }  </style>  </head>  <body>  <span class=hiLite>Wittenstein</span> and <span ID=loLite>Popper</span> never  resolved their differences. And <span class=hiLite>neither</span> cared to.  </body>  </html>

Positioning in Three Dimensions

The absolute position properties in CSS include a location measured from the left side (x), the top (y), and the stack position (z). Generally, the position is measured in pixels (px), but you can use any of the legitimate units of measurement you want. The x and y positions will run in the hundreds of pixels, but the z position is relative to other <div> elements on the page. Like most other units in HTML and JavaScript, the z parameter begins with 0 for the lowest position on a stack of other <div> elements, to the highest number of <div> elements on the page. For example, the following position definition would place the objects in the <div> element about in the middle of an 800 x 600 pixel screen at level 2 in a stack of other <div> elements:

div {       absolute: position;        top:400px;        left:300px;        z-index:2;        }

You must use the <div> element to use absolute position. You can use ID or class selectors to define a position; however, you then must place the selector into a <div> container. The following script shows how to position and stack layers using the absolute position keywords in CSS:

<html>  <head>  <title>Absolute Positioning</title>  <style type="text/css">  #top {       background-color:rgb(130,146,20);        color:black;        font-weight:bold;        font-size: 32pt;        position: absolute;        top:20px;        left:20px;        z-index:2;        }  #middle {       background-color:rgb(213,198,183);        color:black;        font-weight:bold;        font-size: 32pt;        position: absolute;        top:50px;        left:50px;        z-index:1;        }  #bottom {       background-color:rgb(222,48,0);        color:white;        font-weight:bold;        font-size: 32pt;        position: absolute;        top:80px;        left:80px;        z-index:0;        }  </style>  </head>  <body>  <div id=top>At the top! </div>  <div id=middle>Caught in the middle! </div>  <div id=bottom>On the ground floor! </div>  </body>  </html>

You can also create a relative position. To have a relative position, you need a current position as a point of reference. So, if a <div> element is at 100,200 and a relative position of 50,100 is declared, the element would be moved to the position 150,300.

More on Colors

Up to this point, with a couple of exceptions in this chapter, I have used the six-character hexadecimal value or word colors (such as lightseagreen and peru) accepted by HTML to specify colors. However, CSS actually has four formats for colors:

.myColor { color: #rgb }  .myColor { color: #rrggbb }  .myColor { color: rgb(r,g,b) }  .myColor { color: rgb(r%, g%, b%) } 

The first method duplicates each of the values in the red, green, and blue value slots. For example, this value:

#8ac 

translates to

#88aacc 

This technique can come in handy when adhering to a web-safe color palette. Any six-digit hexadecimal value with the following pairs of numbers is considered web-safe:

00 33 66 99 CC FF

Remembering 0, 3, 6, 9, C, and F is relatively easy; by stating a color as #39F, you know that you will be getting #3399FF, a web-safe color.

The third method, rgb(d,d,d), shown in the script in the previous section, uses decimal values instead of hexadecimal ones. Some web art tools (such as Photoshop and Fireworks) use decimal RGB color values, and by copying those values into the formula, you can match a color exactly. Also, some books on color combinations show color values as RGB decimal ones. Leslie Cabarga's book Designer's Guide to Global Color Combinations: 750 Color Formulas in CMYK and RGB from Around the World (North Light Books, 2001) is a good example of a resource that can be used with the rgb(d,d,d) format. For example, the following color combination is from Tibet:

R

G

B

Description

238

222

233

Light plum

210

121

78

Brown

153

158

129

Gray-green

0

0

Black

Using the colors from this palette, it is a simple manner to get the right values, as shown in the following script:

<html>  <head>  <title> RGB Colors </title>  <style type="text/css">  body { background-color: rgb(238,222,233);}  #header {       background-color:rgb(210,121,78);        color: rbg(0,0,0);        font-family:verdana;        font-size:18px;        font-weight:bold;        text-align:center;        font-weight:bold  }  #bText {       background-color:rgb(153,158,129);        font-family:verdana;        font-size:11pt;        color: rgb(238,222,233);        text-indent:2em;        }  </style>  </head>  <body>  <div ID=header>Peace and Wisdom</div><p>  <div ID=bText>&nbsp;<p> Tibet is a culture with a rich spiritual tradition.  <p> Someday it will be free again.<p>&nbsp; </div>  </body>  </html>

Finally, the fourth method of expressing colors in JavaScript is using the rgb(%,%,%) formula. Each of the values expects a percentage between 0 and 100. For those wanting to ensure a web-safe palette, this method is the easiest. Any of the following percentages in combination with one another is web-safe:

0% 20% 40% 60% 80% 100%

For example, having no clue what the following will present as a color, I know that the color is web-safe because each of the values except 0 can be evenly divided by 20:

rgb(80%,20%,60%) 

Even if you do not require web-safe colors for your site, you will find that some color sources express colors as percentages of RGB, and it can be an easier way to envision the amount of red, green, and blue that you want in your "mixed" color.

Borders

As a design element, borders are tricky calls. On one hand, borders represent one of the worse aspects of amateur design in terms of isolating, separating, and generally chopping up a page. On the other hand, if used judiciously, borders can sometimes act as useful or even subtle frames to evoke the right kind of attention to the information without calling attention to itself. CSS provides several border styles, as shown in Table 12.2 Each style is a value of the border-style property.

Table 12.2. Border Styles in CSS

Value

Effect

none

No border (my personal favorite).

hidden

Relevant only for using collapsing border model and inhibiting other borders. (Has precedence over all other styles.)

dotted

Border made up of dotted lines.

dashed

Border made up of dashed lines.

solid

Single line (default) makes borders.

double

Border made up of two solid lines.

groove

Border appears as indent on page.

ridge

Border appears to be raised from page.

inset

Entire border appears as groove in separate borders model.

outset

Entire border appears as ridge in separate borders model.

Besides border-style, you can set values for border-width, border-spacing, and border-collapse. Both the width and spacing values are expressed in terms of standard CSS units of measurement. The collapsing border model allows designers to specify all or part of a cell, row, row group, column, and column group. Borders can reference tables or independent blocks. The following script shows how various characteristics of borders are used in combination with size and color to create the table shown in Figure 12.3:

Figure 12.3. Fairly dramatic objects can be created at very little bandwidth costs using the border elements in CSS.

graphics/12fig03.gif

<html>  <head>  <title> Borders </title>  <style type="text/css">  table {       border: outset 12pt rgb(182,31,0);        border-collapse: separate;        border-spacing: 12pt;        }  TD {       border: inset 7pt rgb(80,101,38);        font-size:60pt;        }  TD.midcell {       border: inset 7pt rgb(255,209,0) //Yellow in the middle        }  </style>  </head>  <body>  <center>  <table>        <tr>              <td>1              <td>2              <td>3        </tr>        <tr>              <td>4              <td class="midcell">5 //Expect the yellow border              <td>6        </tr>        <tr>              <td>7              <td>8              <td>9        </tr>  </table>  </center>  </body>  </html>

Text Formatting

One of the most valuable and underused formats on a web page is the indent. The elegant little notches in a stream of text serve to unify and separate. The indented text serves to demarcate one paragraph from the next, but not so much that the flow of ideas is divorced. The blocks of text that most pages contain have gaps that act as fissures in thought, made even worse by the obnoxious horizontal rule. Using CSS, putting in punctuation formats is simple. Table 12.3 shows the format for indents and various other text-related keywords.

Table 12.3. Text Formats in CSS

Format

Effect

text-indent

Indents first line of paragraph by measurement or percent

text-align

Uses left, right center, or justify

text-decoration

None, underline, overline, line-through, or blink

text-shadow

None, color, length (comma-separated: right, vertical below, blur radius)

text-transform

Capitalize, uppercase, lowercase, or none

letter-spacing

Normal, length

word-spacing

Normal, length

margin

Sets width for all margins

margin-top

Sets width of top margin

margin-bottom

Sets width of bottom margin

margin-left

Sets width of left margin

margin-right

Sets width of right margin

Cascading Style Sheets have more formatting options, and some, such as text-shadow, are not yet fully implemented. However, using the other formatting statements in CSS gives you control over your page's appearance. Using "heavy" margins, the following example places the body text beneath the header without using any centering statements:

<html>  <head>  <title> Formats </title>  <style type="text/css">  #myBlock {       margin-top:2em;        margin-right:10em;        margin-left:10em;        text-align:left;        text-indent:1em;        text-transform:none;        font-family: verdana;        font-size:11pt;        color: dimgray;        font-weight:normal;        }  #myHead {       text-align:center;        text-transform:capitalize;        font-family: verdana;        font-size:16pt;        color: purple;        font-weight:bold;        }  </style>  </head>  <body bgcolor=lightyellow>  <div ID=myHead>  a humble suggestion </div>  <div ID=myBlock>  All paragraphs should be separated by indents. However, good page design allows the  first paragraph after a header to be unindented, but as in this example, you need  ot leave any paragraph without its notch.  <br><div style="text-indent:1em"> See how nicely indents provide a smooth change without  graphics/ccc.gifseparating the flow of ideas. Blocked paragraphs with no indents appear  as fragmented ideas or a set of instructions, and while fine for "how-to" pages,  they are not the best design format for the development of concepts.</div>  </div>  </body>  </html>

One of the more difficult (and annoying) elements of the way CSS handles paragraphs and indents is that it adds an extra space using the <p> tag. To place a new paragraph without using the <p> tag, a <br> tag is used along with a <div> tag to define the indent. If a new <div> segment is set up and defined using the user-defined word myBlock, all of the text is reset using the margins of the initial <div> tag. In other words, it treats the material within the first <div> container as a layer, and the margins are measured from the sides of the layers, not sides of the screen. Figure 12.4 shows the output for the script.

Figure 12.4. With CSS formatting, you can get paragraphs to look like paragraphs.

graphics/12fig04.gif

NOTE

The XHTML standard now requires that all tags be closed. One convention is to use <br /><br /> instead of <p>. This relates to "well-formed" pages that are XML-or XHTML-compliant.

External CSS Style Sheets

When a CSS style sheet or a set of sheets for a web site is developed and refined, you can save a great deal of time by creating a CSS style sheet. As examples in previous chapters have shown, several different web pages can use the same style sheet saving time and bandwidth.

Follow this next set of steps to create an external CSS style sheet:

  1. Write your styles as you would normally, except do not include any HTML tags other than those in CSS definitions.

  2. Save the file as a text file with .css extension.

  3. In the <head> container of your HTML page, enter this tag:

    <link rel="stylesheet" href="URL.css">

That's all there is to it. Design once; use often! The following two scripts show an example of a style sheet and a page that uses the sheet.

In the external sheet, note the absence of HTML tags to format the page. You can redefine HTML tags all you want, but don't use any in creating the style sheet.

external.css
body {       margin:1in;        background-color:rgb(249,230,158);        }  #banner {       text-align:center;        text-transform:capitalize;        font-family: verdana;        font-size:24pt;        color: rgb(159,183,138);        background-color:rgb(115,113,73);        }  .hottext {       margin:1em;        color:black;        background-color:rgb(255,17,0);        text-align:center;        font-family: palatino,times;        font-size:12pt;        }

All references to the following HTML page are in relationship to the previous style sheet. Note the key CSS tag-connection line <link>.

external.html
<html>  <head>  <title> External </title>  <link rel="stylesheet" href="external.css">  </head>  <body>  <div ID="banner">  this banner is from a far and mysterious place  </div>  <div class="hottext">&nbsp<p>  This is just the kind of text I need for the whole site. Thanks to my nifty  external style sheet, I don't have to re-do this style every time I crank up my  Notepad or SimpleText to create some wild and crazy JavaScript that uses CSS.  <p>&nbsp</p>  </div>  </body>  </html>

The bigger the site is, the more useful an external CSS file will be. Any file can be linked to a .css file, and its styles can be incorporated into your own site. (You can even tap into someone else's .css style sheet if you know the URL only with the permission from the author, though.) An external style sheet works just like a web page as far as links are concerned.

The Role of JavaScript in Dynamic HTML

The most frustrating component of DHTML is the Tower of Babel that JavaScript has become in relationship to DHTML. With the fourth generation of both browsers, each (Netscape and Microsoft) uses a solution unique to its own browser. However, with the sixth generation, Netscape seems to have changed its mind about addressing CSS objects. So now, even if you go to all the work of creating multiple scripts to address the different browsers, their own internal consistency is suspect when it comes to JavaScript and CSS because the newer versions of the browser might not be compatible with the older version. Nevertheless, the future, while still the future, holds some promise of a merger. In the area of CSS, both NN6+ and IE5+, including IE6, use a common method of addressing IDs in CSS. The following section shows where this mutual point is and gives some brief history of where IE and NN have come from.

Netscape's Solution

With the advent of NN4, JavaScript's relationship to CSS and DHTML in general seemed to offer a clean solution to these new HTML objects. Basically, this format could assign a value or read a CSS object:

document.tags(ID/class).tagElement.property=value; 

All of the attributes in HTML had to be redefined for JavaScript. For example, this line had to use the multicase word backgroundColor to replace background-color in CSS:

document.tags.body.backgroundColor="green"; 

The following script, which will work in NN4 but not NN6 or IE, illustrates this format:

<html>  <head>  <title> NN4 JS Style </title>  <style type="text/javascript">        document.tags.body.backgroundColor="blue";        document.tags.body.color="yellow";        document.tags.body.fontSize="42pt";        document.tags.body.fontFamily="verdana";        document.tags.body.fontWeight="bold";        document.tags.body.textAlign="center";  </style>  </head>  <body>  Big Bird Rules!  </body>  </html>

Unfortunately, the script not only is browser-specific, but it's version-specific.

Microsoft's Solution

Internet Explorer's format is a bit different, and what works in IE4 also works in IE6. This general format can be used to assign a value to a given element's property:

document.all.element.style.property="value"; 

For example, the CSS selector ID can be used to dynamically change an ID's value. For instance, this line changes all instances of text using the CSS ID defined as myID to purple:

document.all.myID.style.color="purple"; 

Using JavaScript, you can change a lot more than just the color, as the following script shows:

<html>  <head>  <title> IE4 JS Style </title>  <style type="text/css">  #myFont {       font-family:verdana;        color: lightseagreen;        font-size:32pt;        text-align:center;        }  </style>  <script language="JavaScript">  function turnPink( ) {       document.all.myFont.style.color="pink";        document.all.myFont.style.fontFamily="times";        document.all.myFont.style.fontStyle="italic";        document.all.myFont.style.fontSize="60pt";        }  </script>  </head>  <body bgColor="dimgray">  <div ID="myFont" >Color Me Pink!<div><p>  <form>        <input type=button value="Turn Pink" onClick="turnPink( );">  </form>  </body>  </html>
The New DOM Order

To play well together in the sandbox, NN6 and IE6 have adopted a far more object-oriented DOM based on the W3C model. In many ways, the new DOM resembles XML (see Chapter 17, "Working with XML and JavaScript") and grows out of attempts by W3C to better integrate XML, HTML, CSS, and JavaScript. However, before donning party hats to celebrate the d tente between the major browser providers, be aware that some differences might still exist. In other words, go slow on this new DOM until the full features of NN6 and IE6 come to light, and keep in mind that most browsers are still Versions 4 and 5.

The new DOM is a bit more demanding about containers, especially <p> tags, and for a good reason. Because the <p> tag can be used to select a CSS style, it needs both a <p> tag and a </p> tag to demarcate when to begin and end the selected style. More importantly, though, is that containers are a key type of node to be addressed in HTML by JavaScript. Elements that have no ending tag, such as <br>, or text on a page represent nodes as well. However, the containers are the key nodes because they divide the script into child and parent nodes. Parent nodes are containers that encompass another container node. Those encompassed nodes are called child nodes. For example, in the following script, you can see that the <body> node is inside the <html> node. Therefore, references to the parent node point to <html> container and the <body> container as the child node. The following HTML script shows an example of nodes with comments:

<html>                              Parent of Body        <body>                        Child of HTML and parent of Form              <form>                  Child of Body and Parent of Input                    <input type=text> Child of Form and sibling of Input                    <input type=button> Child of Form and sibling of Input              </form>        </body>  </html>

You can see five nodes in this HTML script. They include three container nodes and two independent nodes. The outermost tag is <html>, the parent of the <body> element. In turn, <body> is the parent of the <form> element, and the <form> element is the parent of the two <input> elements. The two <input> elements are siblings to one another because they are encapsulated in the same container, <form>.

One of the methods of the new W3C DOM is getElementById( ), and it begins to solve the mystery of why both classes and IDs are used in CSS. IDs have to be unique to be of any use when referenced. Otherwise, JavaScript would not know what part of a script is referenced when more than a single tag has the same ID; classes, on the other hand, can be used as much as you want in a script because they are not referenced by JavaScript using W3C DOM. The following script shows a sample of what the newer browsers will be capable of doing and, yes, the script is cross-browser compatible with IE5+/NN6+.

<html>  <head>  <title> The New DOM Order: NN6+/IE5+ </title>  <style type="text/css">  #brownOnBlack {       font-family: verdana;        color:peru;        background-color:black;        font-size:20;        font-weight:bold;        }  </style>  <script language="JavaScript">  function newDom( ) {       var addTag=document.createElement("h1"); //Create new element        var solution=document.createTextNode("The Brave New DOM!");//New text        addTag.appendChild(solution);//Put new text into new element        document.body.appendChild(addTag);//Append the whole thing to child        }  </script>  </head>  <body bgColor="peru" >  <h1 ID="brownOnBlack">The Browsers are not getting along!</h1>  <form>        <input type=button onClick="newDom( )" value="What is the Solution?">  </form>  </body>  </html>

The heart of the W3C DOM approach to DHTML is very different from its predecessors. When you run the program, you will see the message "The Brave New DOM!" plastered on your screen in the default <h1> style. If you've ever tried to add text using document.write( ) to a page with existing text, you will have found that it does not work. However, using this newer approach, you can make all kinds of dynamic changes that (cross your fingers) will run just fine on the new browsers from both Netscape and Microsoft.

To see how it works, you need to look at the JavaScript function line by line:

  1. Because the program is going to add a new element, you need to create that element. It does not exist in the HTML page. The element selected is the <h1> tag, but you could have selected another element, such as <p> or any other HTML tag that contains text to be added.

    var addTag=document.createElement("h1"); 
  2. Next, you want to place the text for the newly created node into a variable. This variable will be used to specify the text node that will be appended to an existing node.

    var solution=document.createTextNode("The Brave New DOM!"); 
  3. Now use the appendChild( ) method with the new element to identify the new element and what it is to do.

    addTag.appendChild(solution); 
  4. Finally, you run down the hierarchy to pinpoint where you want to append the new child node in the HTML script. Hence, you need to use appendChild() a second time in the script. The top is <html> (document), <body> (body), and, finally, the child of <body> where the new material is placed.

    document.body.appendChild(addTag); 

At the time of this writing, IE6 is still in its infancy, and NN6 is going through growing pains as well. However, signs indicate that the future is very bright with the adoption of W3C DOM standards by both major browser manufacturers. The full integration brought about by having different elements of web scripting (XML, HTML, CSS, and JavaScript) adhere to a common DOM will add immeasurable value to JavaScript's utility as a dynamic tool in the future.

Summary

Whatever else you take away from this chapter, just remember that Cascading Style Sheets are the designer's best friend. This is true for several reasons. First, CSS provides the tools for designers to create pages that give the designer a good deal of control. Unlike non-CSS design, which relies on using a convoluted system of tables or using bandwidth-heavy graphics, CSS provides absolute positioning and a wide assortment of style, color, and background options. Second, CSS uses less bandwidth than scripts using graphics. Instead of relying on graphics, even ones boiled down to very low file sizes, CSS is nothing but cheap and light text instructions. Third, CSS is reusable. By employing external style sheets, a whole design palette can be reused after initial development. For real-world projects in which time is money, this feature alone sets CSS apart from other design solutions.

At this point in time and, for the next couple of years, designers using DHTML and JavaScript are going to have to either create multiple functions for cross-browser compatibility or hang back until both browsers have at least Version 6 installed in the bulk of the population. By adopting the Level 2 W3C DOM (and emerging Level 3 DOM), both Netscape and Microsoft have shown signs of maturity, optimistically pointing to a time when one design will be cross-platform and cross-browser compatible. In the meantime, learn all you can about the W3C DOM specifications at http://www.W3C.org. You will be glad you did as this new DOM comes to represent a truly universal language of the web.

CONTENTS


JavaScript Design
JavaScript Design
ISBN: 0735711674
EAN: 2147483647
Year: 2001
Pages: 25

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