JavaScript by Example (2nd Edition)

The W3C DOM (level 1) provides JavaScript applications a standard way to access all the elements of the document. In order for JavaScript to change the style of a document dynamically, the HTML tags must be represented as objects. We have already discussed the hierarchical tree-like structure of the document object model in Chapter 11, "The Document Objects: Forms, Images, and Links."

15.4.1 How the DOM Works with Nodes

Now we will take the DOM to a new level. Just as we used the DOM to access forms, images, and links as objects, now we can use the DOM to access every element in an HTML document. The standard DOM level 1 currently consists of two parts : the DOM core and the DOM HTML (see http://www.w3.org/TR/REC-DOM-Level-1/introduction.html). The DOM core specifies a standard way to manipulate document structures, elements, and attributes; the DOM HTML just extends that functionality to HTML. Recall that the DOM represented an HTML document as a tree: with the DOM, every HTML element can be defined as part of the tree, as shown in Figure 15.23.

Figure 15.23. The tree-like hierarchy of the document object model.

The purpose of the hierarchal tree is to provide a logical structure to represent a document and a way to navigate that structure, and to add, modify, or delete elements and content from it. Starting with the document at the top of the tree, you can traverse down the tree to every element until you reach the element, attribute, or text you are seeking. The core DOM identifies each element in the tree as a node object. There are parent and child nodes, sibling nodes, and more (see Table 15.10).

Table 15.10. Some DOM objects.

Object

Definition

Node

The primary data type that represents an HTML element

Document

The root of the document tree

Element

An element within an HTML document

Attribute

Attributes of an HTML tag

Text

The text between markup tags, such as the text between <h1> and </h1>

The DOM views every HTML element shown in Figure 15.24 as a node. In the tree, the top node is the <html> tag, called the root node of the document. Below it are the <head> and <body> tags, which are called child nodes of the HTML element. In the <title> is the text My Title, which is also a node, called a text node . Since it is the last node, the tree-like structure terminates at that node, also called a leaf node . The nodes are divided into three types of nodes: the element node , attribute node , and the text node . These types are numbered 1, 2, and 3, for element, attribute, and text node, respectively. In the example, the <title> and </title> tags are element nodes, and the text between the tags, My Title , is an example of a text node. An attribute node is represented as a property of the HTML element to which it is assigned. The <a> tag has an href attribute. In the example, <a href="http://www.prenhall.com">, href is an attribute node and the URL is called its nodeValue . (The text nodes are not supported on all browsers.)

Figure 15.24. The node hierarchy.

Refer to Tables 15.11 and 15.12 for a list of node properties and node methods .

Table 15.11. Node properties.

Property

What It Does

firstChild

Returns the first child node of an element

lastChild

Returns the last child node of an element

nextSibling

Returns the next child node of an element at the same level as the current child node

nodeName

Returns the name of the node

nodeType

Returns the type of the node as a number: 1 for element, 2 for attribute, 3 for text

nodeValue

Sets the value of the node in plain text

ownerDocument

Returns the root node of the document that contains the node

parentNode

Returns the element that contains the current node

previousSibling

Returns the previous child node of an element at the same level as the current child node

Table 15.12. Node methods.

Method

What It Does

appendChild(new node)

Appends a new node onto the end of the list of child nodes

cloneNode(child option)

Makes a clone of a node

hasChildNodes()

Returns true if the node has children

insertBefore(new node, current node)

Inserts a new node in the list of children

removeChild(child node)

Removes a child node from a list of children

replaceChild(new child, old child)

Replaces an old child node with a new one

Siblings

A sibling is a node on the same level as another node. In the example,

<p> <em>this is </em>some <b>text</b> </p>

the parent node is <p> and has two children, the <em> node and the <b> node. Since the <em> and <b> are at the same level within the text, they are called siblings, like brother or sister nodes.

Parents and Children

When looking at the structure of the tree hierarchy, some nodes are above others. A node above another node is a parent node, and the ones below the parent node are its children. See Figure 15.25. Any HTML tags that have both an opening and a closing tag are always parent nodes, for example, <p> and </p> .

Figure 15.25. Tree hierarchy of nodes.

Attributes of an element are not child nodes, but are considered to be separate nodes in their own right. For example, the href attribute of the <a> tag is an attribute node, not a child of the <a> tag.

The nodeName and nodeType Properties

When walking down DOM tree, you can find out the name of a node and the type of the node with the nodeName and nodeType properties. Table 15.13 gives the value for each of the properties.

Table 15.13. nodeName and nodeType properties.

Node

nodeName Property

nodeType Property

Attribute

Name of the attribute ( id, href )

2

Element

Name of the element ( h1, p )

1

Text

#text

3

Example 15.22

<html> <head><title>The Nodes</title></head> <body><font size="+2"> <h1>Walking with Nodes</h1> <p>Who knows what node?</p> 1 <script name="javascript"> 2 var Parent= document.childNodes[0] ; 3 var Child= Parent.childNodes[0] ; document.write("The parent node is: "); 4 document.write( Parent.nodeName +"<br>"); document.write("The first child of the parent node is: "); 5 document.write( Child.nodeName +"<br>"); document.write("The node below the child is: "); 6 document.write( Child.childNodes[0].nodeName +"<br>"); document.write("The text node below title is: "); 7 document.write( Child.childNodes[0].childNodes[0].nodeName +" <br>"); document.write("The first child of the parent is: "); 8 document.write( Parent.firstChild.nodeName +"<br>"); document.write("The last child of the parent is: "); 9 document.write( Parent.lastChild.nodeName +"<br>"); document.write("The node below the body is: "); 10 document.write( Parent.lastChild.childNodes[0].nodeName + "<br>"); document.write("The next sibling of the h1 element is: "); 11 document.write( Parent.lastChild.childNodes[0].nextSibling. nodeName ); document.write("<br>The last child's type is: "); 12 document.write( Parent.lastChild.nodeType ); </script> </body> </html>

EXPLANATION

  1. The JavaScript program will access the HTML elements through the DOM where each element is viewed as a node.

  2. The first node, childNodes[0] , is the first node in the HTML hierarchy, the parent node. This node is assigned to a variable, Parent . The only reason to create the variable is to cut down on the amount of typing and propensity for errors when we go further down the document tree. Note: Watch your spelling when working with the DOM in JavaScript.

  3. The parent node's first child is document.childNodes[0].childNodes[0] . This portion of the tree is assigned to the variable Child .

  4. The name of a node is found in the nodeName property. The parent node is HTML , the highest element in the HTML hierarchy.

  5. The nodeName of the first child of the parent node is HEAD .

  6. The next node in the hierarchy is the child of the HEAD element. It is the title element:

    <html> <head> <title>

  7. Continuing the walk down the DOM tree, we come to the text node. It contains the text between the <title> </title> tags. The name of the text node is preceded by a # mark.

  8. Using the firstChild property to simplify things, the first child of the parent again shows to be the HEAD element.

  9. The last child of the HTML parent is the BODY element:

    <html> <head> <body>

  10. The node directly below the body is the FONT element:

    <body><font size=+2</font>

  11. The node below the body, document.childNodes[0].lastChild.nodeName , is the H1 element.

  12. The parent's last child node's type is 1. An element node type is type 1, an attribute type is type 2, and a text node is type 3. See Figure 15.26.

    Figure 15.26. Using the nodes to access HTML elements.

Working with the Elements

As you know, an HTML document is largely a set of elements, enclosed in < >, called tags. H2 is an element, <H2> is a tag. The DOM is represented as a hierarchal tree of these elements, where each element is represented as a node. But walking with the nodes is just too much trouble most of the time, so the W3C DOM provides additional methods and properties to help make the walk easier.

Table 15.14. HTML element properties to represent HTML attributes.

Property

Description

Example

className

Represents the class of a CSS element

div2.className="blue";

div2 refers to an HTML element. It is being assigned the CSS class called blue (see Example 15.29)

dir

Specifies the text direction for a document; e.g., read left to right (English), or right to left (Hebrew)

element.dir="ltr";

id

Value of the unique id of the current element

(see Section 15.4.2)

lang

Specifies the language in which the text of the document is written; e.g., en for English, ja for Japanese, and sp for Spanish

if(document.lang=="ja")

style

Value of the CSS inline style attribute (CSS2)

div.style. color ="green"; (see Section 15.4.4)

title

Returns the title of the document found between the <title> and </title> tags

<title>My Book</title> strTitle = document.title strTitle contains "My Book"

15.4.2 All Those DOMs

You will often hear terms, like the Netscape DOM, the IE DOM, and the standard DOM. Before the W3C was able to create a standard, fourth-generation browsers introduced their own DOMs. Netscape 4, for example, implemented a layer DOM to control the positioning and visibility of elements, whereas Internet Explorer provided the all DOM to control positioning, visibility, and appearance of elements. They were not compatible and when you created a page, you had to perform cross-browser checking to determine which DOM should be used. This book addresses the W3C DOM, which has been embraced by most modern browsers, including NN6+ and IE5+. [2]

[2] See http://www.mozilla.org/docs/dom/domref/dom_el_ref.html for a complete DOM elements interface.

All browsers that comply with the W3C's DOM should implement the ID method for accessing the elements in a document. (See the next section for details.)

Here is a little test code you can run to see if your browser is W3C DOM compliant:

isNetScape = (document.layers) ? true:false; isInternetExplorer = (document.all) ? true: false; if (document.getElementById){ alert("DOM compliant!"); // Netscape 6+ and IE5+

Go to http://developer.apple.com/internet/javascript/sniffer.html to see examples of "browser sniffer" programs ”programs that can tell what browser is being used.

The getElementById() Method

All that node stuff can be really tricky and vary on different browsers, but by combining the HTML id attribute with the getElementById() method of the document object, it is much easier to get a handle on any HTML object. The getElementById() method returns a reference to the HTML element that can then be manipulated by a JavaScript program. Suppose you have a <body> tag defined with an id attribute, as:

<body id="bdy1">

Now in JavaScript you can reference the body element with the getElementById() method as follows :

bdyreference = document.getElementById("bdy1")

Before the DOM was standardized, Internet Explorer (version 4+) provided another mechanism for accessing all HTML elements within the document, called the all property of the document object. The statement shown above written for IE could be written:

bdyreference = document.all["bdy1"];

And Netscape 4 provided yet another format:

bdyreference = document.layers["bdy1"]

Starting with IE5+ and NN6+, the W3C's getElementID() method is used rather than the all or the layers property. The newer browsers support the W3C standardized DOM although many Web pages were written using the older formats.

Example 15.23

<html> <head><title>The Dom and Id's</title></head> 1 <body id="body1"> 2 <h1 id="head1">Heading Level 1</h1> 3 <p id="para1"> This is a paragraph </p> </body> <script name="javascript"> 4 var h1tag=document.getElementById("head1"); 5 var bodytag=document.getElementById("body1"); 6 var paratag = document.getElementById("para1"); 7 h1tag.style.fontFamily="verdana"; h1tag.style.fontSize="32"; paratag.style.fontSize="28"; paratag.style.color="blue"; bodytag.style.backgroundColor="pink"; 8 document.write( document.getElementById("body1" )+"<br>"); document.write( document.getElementById("head1") +"<br>"); document.write( document.getElementById("para1") +"<br>"); </script> </body> </html>

EXPLANATION

  1. The <body> tag is given an id called "body1" .

  2. The <h1> tag is given an id called "head1" .

  3. The <p> tag is given an id called "para1" .

  4. In the JavaScript program, the getElementById() method returns a reference to an H1 element, and assigns that value to the variable called h1tag .

  5. The getElementById() method returns a reference to a BODY element, and assigns that value to the variable called bodytag .

  6. The getElementById() method returns a reference to a P element, and assigns that value to the variable called paratag .

  7. Now, by using the style property (for a complete discussion, see "The style Object and CSS" on page 553), the elements are assigned new values for font size and color, causing them to change change dynamically.

  8. The value returned by the getElementById() method is displayed for each of the elements by using their respective IDs. As shown in the output, each one of these HTML elements is an object. See Figure 15.27.

    Figure 15.27. HTML elements are objects.

The getElementsByTagName() Method

To reference a collection of elements, such all the <p> tags, <h1> tags, or <a> tags in your document, you can use the getElementsByTag Name() method. This method takes the name of the element as its argument and returns a list of all the nodes of that name in the document. If you need to collectively change the values of a particular element, such as all the links in an <a> tag, do this by manipulating the reference returned by the getElementsByTagName().

Example 15.24

<html><head><title>Working with Tags</title> </head> <body bgcolor=lightblue> 1 <h1> First</h1> <h1> Second</h1> <h1> Third</h1> <font size="+2"> 2 <script language="JavaScript"> var heading1=document.getElementsByTagName("h1"); 3 document.write( heading1 + "<br>"); document.write("There are "+ 4 heading1.length + " H1 tags.<br>"); </script> </body> </html>

EXPLANATION

  1. Three <h1> tags are used in this document.

  2. Because of the top-down processing by the HTML renderer, be sure to put the JavaScript program at the end of the document. This way, the tags will already have been identified before they are put into the HTML collection returned by the getElementsByName() method.

  3. The HTML collection of H1 tags is stored as an array of nodes in the variable, heading1 .

  4. The length of the array is 3 in this example because there are three H1 elements in the document. See Figure 15.28.

    Figure 15.28. Netscape 7 (left), IE 6 (right).

15.4.3 Scrolling with the Nodes

Although the title of this section may sound more like a title for a Star Trek drama, it is really about dynamic HTML. By using the getElementById() method and a little node knowledge, a scrolling marquee is created in Example 15.25. In Chapter 10 we saw scrolling in the window's status and title bar. Now we can scroll within the body of the document. In the following example, a message will continuously scroll across the screen. The original message is placed within a <div> container. By first identifying the HTML div element ” getElementById() ”JavaScript can then reference its child node, which is the text of the message ( firstChild ). This is depicted in Figure 15.29.

Example 15.25

<html><head><title>Scrolling Text</title> <style> 1 #div1 { background-color:darkgreen; color: white; font-family:courier; font-weight: bold; position:absolute; border-style:groove; border-color:white; padding-left:10px; top:20px; left:10px; 2 width: 595px; height: 6%; 3 overflow: hidden; } 4 img { position: absolute; top: 10px;left:60px; border-style:solid;border-color="darkgreen";} </style> <script language="JavaScript"> <!-- 5 /*Modification of text box marquee by Dave Methvin, Windows Magazine */ 6 var scroll_speed = 200 ; // 200 milliseconds var chars = 1; 7 function init(){ divElement=document.getElementById("div1"); } 8 function scroller() { 9 window.setTimeout('scroller()',scroll_speed); 10 var msg=divElement.firstChild.nodeValue; 11 divElement.firstChild.nodeValue = msg.substring(chars) + msg.substring(0,chars); } 12 scroller(); //--> </script> </head> 13 <body bgcolor="#669966" onLoad="init() ";> <img src="BubyanIsland.JPG" width="450" length="500"> 14 <div id="div1"> The latest news from Baghdad is not good tonight. Sand and rain are hindering our troops. The number of refugees continues to increase in the north... </div> </body> </html>

Figure 15.29. Referencing a child node requires first identifying the div element.

EXPLANATION

  1. An ID selector is defined with a style for the div element on line 14.

  2. The size of the div container is defined.

  3. If the text within the div container will not fit within the dimensions of the box, the overflow property will adjust it to fit.

  4. The image is fixed at this absolute position on the screen and has a dark green, solid border.

  5. The scroller() routine (line 8) was found at the Java Planet Web site and submitted by Dave Methvin. (Thank you Dave, wherever you are!) I have greatly modified the original.

  6. The initial values used for the scroller() function are assigned values. One is the speed for the timer, the other the value of an argument to the substr() method.

  7. This function, called init() , is called after the document has been loaded. Its purpose is to get a reference to the div element. The getElementById() method returns a reference to the div element.

  8. The function called scroller() is defined. Its function is to cause the text found in the <div> container to scroll continuously from the right-hand side of the container.

  9. The window's setTimeOut() method is used to call the scroller() function every 200 milliseconds (.2 seconds). It's the timer that creates the action of actually scrolling.

  10. The div element is a parent node. It has a child node. The value of its first child, divElement.firstChild.nodeValue , is the textual content of the message; that is, the text found between the <div></div> tags. The variable msg gets the value of the child node.

  11. The value returned by msg.substr(1) is " he latest news from Baghdad is not good tonight. Sand and rain are hindering our troops. The number of refugees continues to increase in the north..." Notice that the first character in the message has been removed. The next substring method will return the first character ” substring(0,1 ) ”and append it to the first value resulting in " he latest news from Baghdad is not good tonight. Sand and rain are hindering our troops. The number of refugees continues to increase in the north... T ". All of this is assigned back to the value of the child node. In 200 milliseconds, the scroller() function is called again, and the message becomes " e latest news from Baghdad is not good tonight. Sand and rain are hindering our troops. The number of refugees continues to increase in the north... Th " , and so on.

  12. The scroller() function is called for the first time here.

  13. In the <body> tag, the onLoad event is triggered as soon as the document has loaded.

  14. The <div> tags contain the text of the message that will be scrolled. Its ID, "div1" , defines the CSS style that will be used, and is the unique identifier that will be used by JavaScript to get a reference to it. See the output in Figure 15.30.

    Figure 15.30. A scrolling marquee continues to print news across the image. (The U.S. Marine is Major Tom Savage, my son, alongside a fellow officer.)

15.4.4 The style Object and CSS

The style object contains a set of properties corresponding to the CSS attributes supported by your browser. Each HTML object has a style property (starting with IE4 and NN6) used to access the CSS style attributes assigned to it; for example, an H1 element may have been defined with a CSS font-style, color , and padding . The style object has properties to reflect each of the CSS atributes. See Table 15.15.

Many of the CSS style attributes, such as background-color, font-size , and word-spacing , contain hyphens in their names . Like all objects we have seen in JavaScript, there is a convention for spelling the name of the object. The name would not contain a hyphen, and multiple words after the first word are usually capitalized. Therefore, the CSS naming convention is different with the properties of the style object. The hyphen is removed and the first letter of each word after the hypen is capitalized. For example, the CSS attribute, background-color, when used as a style property, is spelled backgroundColor, font-size is fontSize, and border-right-width is borderRightWidth.

FORMAT

elementname.style.property="value";

Example:

div2.style.fontFamily = "arial";

Table 15.15. style object properties.

Property

Example CSS Value

HTML Tags Affected

Fonts

font

12pt/14pt sans-serif, 80% sans-serif, x-large/110% arial, normal small-caps

All

fontFamily

serif, sans-serif, cursive , fantasy, monospace

All

fontSize

12pt, larger, 150%, 1.5em

All

fontStyle

normal, italic, oblique

All

fontVariant

normal, small-caps

All

fontWeight

normal, bold, bolder, lighter, 100, 200...900

All

Colors

backgroundColor

red, blue, #F00

All

color

red, green, #F00, rgb(255,0,0)

All

Images

backgroundAttachment

scroll, fixed

All

backgroundImage

URL (bay.gif), none

All

backgroundPosition

right top, top center, center, bottom, 100% 100%, 0% 0%, 50% 50%

Block-level and replaced elements

backgroundRepeat

repeat, repeat-x (horizontally), repeat-y (vertically), no-repeat

All

Text Alignment

letterSpacing

normal, 0.1em

All

lineHeight

normal, 1.2, 1.2em, 120%

All

textAlign

left, right, center, justify

All

textDecoration

underline, overline, line-through, blink

All

textIndent

3em, 15%

Block-level elements

textTransform

capitalize, uppercase, lowercase, none

All

verticalAlign

baseline, sub, super, top, text-top, middle, bottom, text-bottom, 50%

Inline elements

wordSpacing

normal, 2em

All

Margins and Borders

align

 

All

borderStyle

none, solid, 3D

All

borderWidth

thin, medium, thick, 2em

All

margin

5em, 3em, 2em, 1em (top, right, bottom, left)

All

marginBottom

100px, 50%

All

marginLeft

.5in, 40%

All

marginRight

20em, 45%

All

marginTop

1cm, 20%

All

padding

2em, 4em, 6em (right, bottom, left)

All

paddingBottom

2em, 20%

All

paddingLeft

.25in, 20%

All

paddingRight

.5cm, 35%

All

paddingTop

20px, 10%

All

length

 

Block-level elements

width

12em, 30%, auto (initial width value)

Block-level element

For a complete list of properties, see http://www.w3.org/TR/REC-CSS2/propidx.html.

Example 15.26

<html> <head><title>Changing Background Color Dynamically</title> 1 <script language="JavaScript"> 2 function bodyColor(){ 3 var i = document.form1.body.selectedIndex; 4 bodycolor = document.form1.body.options[i].value; 5 document.getElementById("bdy").style.backgroundColor = bodycolor; } </script> </head> 6 <body ID="bdy"> <p> Pick a background color for this page. </p> 7 <form name="form1"> <b> Color </b> 8 <select name="body" onChange="bodyColor();"> <option value="pink">pink</option> <option value="lightblue">blue</option> <option value="yellow">yellow</option> <option value="lightgreen">green</option> </select> <br> </form> <p> This is a test. </p> </body> </html>

EXPLANATION

  1. The JavaScript program starts here.

  2. A JavaScript user -defined function called bodyColor() is defined.

  3. The number, selectedIndex , of the option chosen from a select list is assigned to variable i .

  4. The value of the selected option is one of the colors listed in the select list on line 8.

  5. The getElementById() method returns a reference to the body tag, whose ID is bdy . With the style property, the background color of the document is changed with this statement.

  6. The body tag is given an id attribute by which to identify it.

  7. An HTML form called form1 starts here.

  8. A select menu is defined to give the user options to change the background color of the document on the fly. The onChange event is triggered when one of the options is selected, and is handled by invoking the function bodyColor() . The output is shown in Figure 15.31.

    Figure 15.31. Changing the background color dynamically (left); now the color is green (right).

Positioning Text with the style Property

By assigning a position to the style property it is possible to place an element in different sections of the page. In the following example, by assigning positions , the text is moved after the document has been loaded.

Example 15.27

<html><head><title>Positioning</title> 1 <script language="javascript"> var div1,div2,div3; 2 function init(){ 3 div1=document.getElementById("first"); div2=document.getElementById("second"); div3=document.getElementById("third"); } 4 function movePosition(){ 5 div1.style.left = 50; div1.style.top = 150; 6 div2.style.left = 100; div2.style.top = 100; 7 div3.style.left = 150; div3.style.top = 50; } </script> </head> 8 <body onLoad="init()"> <font size="+2"> 9 <div id="first" >one</div> <div id="second" >two</div> <div id="third" >three</div> <form> <input type="button" value="move text" 10 onClick="movePosition()"> </form></body> </html>

EXPLANATION

  1. The JavaScript program starts here.

  2. The first function defined is init() . It will be called after the document has been loaded.

  3. The getElementById() method returns references to three div block objects.

  4. A function called movePosition() is defined. It is responsible for moving the text to different positions on the screen.

  5. The first block of text will be positioned at 50 pixels from the left-hand side of the screen and 150 pixels from the top.

  6. The second block of text will be positioned at 100 pixels from the left-hand side of the screen and 100 pixels from the top.

  7. And the third block of text will be positioned 150 pixels from the left-hand side of the screen and 50 pixels from the top.

  8. The onLoad event is triggered just after the page has been loaded, and will invoke the init() function.

  9. The div containers are assigned absolute positions on the page. Each div block will contain a string of text.

  10. When the user clicks on the button labeled "move text", the onClick event will be triggered, causing the text to be moved to a different location on the page. See Figure 15.32.

    Figure 15.32. Before clicking the button (left); after clicking the button (right).

Now we will change the position values in the program, as shown in Example 15.28. The output is shown in Figure 15.33.

Example 15.28

(See Example 15.27 for the complete program.) function movePosition(){ div1.style.left = 50; div1.style.top = 50; div2.style.left = 100; div2.style.top = 100; div3.style.left = 150; div3.style.top = 150; }

Figure 15.33. After changing the x,y positions in the program.

Changing Color with the className Property

The className property is defined for all HTML elements. With the className property, you can change an element dynamically by assigning it the name of a class defined in a CSS. The following example contains a cascading style sheet with three classes.

Example 15.29

<html><head><title>Coloring Text</title> <style type="text/css"> body { background-color: yellow; font-size: 22pt; font-weight: bold; } 1 .red { color:rgb(255,0,0); /* Defining classes */ font-style: verdana; font-size: 32; } 2 .blue { color:blue; font-style: verdana; font-size: 36; } 3 .green { color: green; font-style: verdana; font-size: 40; } </style> <script language="javascript"> 4 function init(){ div1=document.getElementById("first"); div2=document.getElementById("second"); div3=document.getElementById("third"); } 5 function colorText(){ div1.style.left = 50; div1.style.top = 50; 6 div1.className="red"; div2.style.left = 100; div2.style.top = 100; 7 div2.className="blue"; div3.style.left = 150; div3.style.top = 150; 8 div3.className="green"; } </script> </head> 9 <body onLoad="init()"> <div id="first" >It's a one,</div> <div id="second" >and a two,</div> <div id="third" >and three!</div> <form> <input type="button" value="move and color text" 10 onClick="colorText()"> </form> </body>

EXPLANATION

  1. A CSS class for a style is defined. Text will be a red, Verdana font, point size 32. The rgb (red, green, blue) color is used here for demonstration. It would be easier to just assign red to the color property.

  2. A CSS class for another style is defined. The text will be a blue, Verdana font, point size 36.

  3. A CSS class for a third style is defined. The text will be a green, Verdana font, point size 40. Notice that each class not only changes the color of the font, but increases its point size.

  4. When the onLoad event is triggered, just after the document has been loaded, the user-defined init() function is called. The getElementById() method returns references to three div objects.

  5. A function called colorText() is defined. It sets the position of the div containers and defines the color for the text in each container.

  6. The className property is used to reference the CSS class named red , defined in the document.

  7. The className property is used to reference the CSS class named blue , defined in the document.

  8. The className property is used to reference the CSS class named green , defined in the document.

  9. The onLoad event is triggered just after the document is loaded. It will invoke the init() function.

  10. When the user clicks on this button, the onClick event is triggered. It invokes the colorText() function, which will move and change the text in each of the div containers.

Figure 15.34. The initial appearance of the document (left); after clicking the button, the color, position, and size of the text is changed (right).

15.4.5 Event Handling and the DOM

We have been discussing events since Chapter 1. They are what allow the program to react to user-initiated events. After browsers got to their fourth version, the events became full-fledged objects. The event object has knowledge about the event: what caused it, what triggered it, where it occured on the screen, and even the parent of the tag that triggered it. The event object, like other objects, has a collection of properties and methods associated with it. Not all browsers support the same event model and not all browsers refer to the event in the same way or even use the same properties.

Trickling and Bubbling

The way that the events are captured differs by the browser. In Netscape 4, for example, the event comes to life at the window level and is sent down the tree of nodes until it finally reaches the target object for which it was intended; whereas with IE the event springs to life for the target it was intended to affect, and then sends information about the event back up the chain of nodes. With Netscape 4, the event trickles down from the top to its target, and with the IE approach the event bubbles up from its target. Handling the way events propagate is another browser compatibility issue.

The W3C DOM level 2 provides an Events module that allows the DOM nodes to handle events with a combination of these methods, but defaults to the bubble up propagation model. This is supported by Netscape 6+, but not IE 6.

There are a number of event types defined by the DOM HTML Events module, as shown in Table 15.16.

Table 15.16. Event properties.

Name

What It Describes

bubbles

Boolean to test whether an event can bubble up the document tree

canceleable

Boolean to test whether the event can be cancelled

currentTarget

The node currently being processed by a handler (NN)

eventPhase

A number specifying the phase of the event propagation

fromElement

Refers to the object where the mouse was pointing before the mouseover event was triggered (IE)

srcElement

Refers to the object of the tag that caused the event to fire

target

The node on which the event occurred, not necessarily the same as currentTarget

timeStamp

When the event occurred (a Date object)

type

The type of the event that occurred, such as click or mouseOut

In the following example, mouseOver and mouseOut events will be used to change the style of a block of text to give it emphasis. When the mouse rolls over a specific block of text, the event handler invokes a function that can check to see what block of text the mouse is on and detect when it leaves the box. The node where the event occurred can be found in the currentTarget property (NN) or the fromElement property (IE).

Example 15.30

<html><head><title>Positioning</title> 1 <link rel=stylesheet type="text/css" href="externstyle.css"> <script language="javascript"> function init(){ div1=document.getElementById("first"); div2=document.getElementById("second"); div3=document.getElementById("third"); } 2 function colorText(e){ 3 if(e.currentTarget.id == "first") { // Use e.fromElement.id (IE6) 4 div1.className="red"; } else if(e.currentTarget.id == "second"){ div2.className="blue"; } else{ div3.className="green";} } 3 function unColorText(e){ if(e.currentTarget.id == "first"){ // use e.srcElement.id (IE6) div1.className="black"; } else if(e.currentTarget.id == "second"){ div2.className="black"; } else{ div3.className="black"; } } </script> </head> <body onLoad="init()"> 4 <div id="first" 5 onMouseover="unColorText(event);" 6 onMouseout="colorText(event);">Roll over me! </div> <div id="second" onMouseover="unColorText(event);" onMouseout="colorText(event);">and then me,</div> <div id="third" onMouseover="unColorText(event);" onMouseout="colorText(event);">and me too.</div> </body> </html>

EXPLANATION

  1. The style for this document is coming from an external style sheet. It's the same style used in the previous example and can be found on the CD-ROM in the back of this book.

  2. A function called colorText() is defined. It takes one argument, a reference to the event that caused it to be invoked.

  3. The current.Target.id is a property that references the id of the tag where this event occurred: the <div> tag with the id of "first" . If this doesn't work for you, use the IE fromElement property for the mouseOver event. To get the id name for the div container, use e.fromElement.id. For the mouseOut event, use the src.Element property and e.srcElement.id.

  4. The first div container is defined with an id name "first" .

  5. When the mouse is moved onto the second div container, the onMouseover event is triggered and the colorText() function is called. It passes a reference to the event object to the function allowing the function to know more about the event that just occurred and what div container it applies to.

  6. When the mouse is moved away from the div container, the onMouseout event is triggered, and the function colorText is called, passing a reference to the event object. The output is shown in Figure 15.35.

    Figure 15.35. Before the mouse rolls over the first <div> block (top left); when the mouse rolls over the first <div> block (top right); when the mouse leaves the first div container and rolls over the next one (midddle left); now the mouse has rolled over the last <div> container (middle right); after the mouse has left all three containers (bottom).

15.4.6 Back to the z-index and Dynamic Positioning

In the CSS section of this chapter, the zIndex property was described to create a three-dimensional effect with a stack of <div> containers. In the following example a JavaScript program manipulates the containers so that they can be moved into different positions.

Example 15.31

<html><head><title>layers</title> <script language="JavaScript"> 1 function moveUp(id){ 2 var box= document.getElementById(id); 3 if(box.style.zIndex == 100){ // Can't stack higher than 100 4 box.style.zIndex=2; } 5 else if(box.style.zIndex != 3){ box.style.zIndex=100; } else{ 6 box.style.zIndex=0; } } </script> </head> <body bgcolor=lightgreen> 7 <span id="red" 8 onClick="moveUp(id);" ></span> 9 <span id="yellow" onClick="moveUp(id); "></span> 10 <span id="blue" onClick="moveUp(id); "></span> 11 <span id="white" onClick="moveUp(id); "></span> </body> </html>

EXPLANATION

  1. The JavaScript user-defined function called moveUp() is defined. It has one parameter, the id of the tag from where it was called.

  2. The getElementById() method returns a reference to the object that called this function and assigns it to the variable, called box .

  3. If the zIndex of the object evaluates to 100, it must be at the top of the stack, because that is as high as the stack gets.

  4. This sets the stack level of the zIndex to 2, causing it to move toward the bottom of the stack.

  5. If the zIndex for the object is not 3, it is not at the top. Its zIndex will be set to 100, moving it to the top of the stack.

  6. The object is moved to the bottom of the stack with a zIndex of 0.

  7. The <span> tag is used to create a rectangular red box on the screen. With a zIndex of 0, it will be positioned at the bottom of the stack.

  8. When the user clicks on the button, the onClick event is triggered, and the handler function, moveUp(id) , is called.

  9. A yellow rectangular box is created with the <span> tag. With a zIndex of 1, it will be positioned above the last block in the stack.

  10. A blue square box is created with the <span> tag. With a zIndex of 2, it will be positioned above the last block in the stack.

  11. A small white rectangular box is created with the <span> tag. With a zIndex of 3, it will be positioned at the top of the stack. See Figure 15.36.

    Figure 15.36. The original configuration of the four rectangles (left); after manipulating the rectangles by reassigning the z-index (right).

15.4.7 Setting Visibility

The visibility property lets you hide an object and then bring it back into view. You can also use the visibility property to determine the state: it "visible" or "hidden"? [3] This property is useful when creating interfaces such as drop-down menus , slide shows, and pop-ups such as extra text to explain a link or image map. [4]

[3] Netscape 4 specifies a value of show or hide with the visibility property of the Layer object.

[4] The visibility property applies to an entire object. The clip property allows you to designate how much of an element will be visible.

Drop-Down Menus

Drop-down menus are commonly used in Web pages to create submenus that appear and then disappear when no longer needed. The following example demonstrates the use of the visibility property to create this type of menu. When the user clicks on one of the links in the main menu, a drop-down menu will appear. If he double-clicks anywhere within the drop-down menu, it will be hidden from view. Each of the drop-down menus is defined within a <div> container.

Example 15.32

<html><head><title>Drop-Down Menu</title> <style type="text/css"> 1 a { font-family: verdana, arial; color: darkblue; font-weight: bold; margin-left: 4px; } /* link style for main menu */ 2 #menu, .menu { font-stye: verdana; font-size:10pt; color:black; } /* link style for drop-down menu */ 3 #menu { position:absolute; top:40px; border-style:solid; border-width:1px; padding: 5px; background-color:yellow; width:75px; color: black; font-size: 12pt; 4 visibility:hidden; } 5 #menu2 { position:absolute; top:40px; left:3.2cm; border-style:solid; border-width:1px; padding: 5px; background-color:orange; width:80px; color: black; font-size: 12pt; visibility:hidden; } 6 #menu3 { position:absolute; top:40px; left:6.2cm; border-style:solid; border-width:1px; padding: 5px; background-color:pink; width:80px; color: black; font-size: 12pt; visibility:hidden; } 7 </style> <script language="JavaScript"> 8 function showMenu(id){ 9 var ref = document.getElementById(id); 10 ref.style.visibility = "visible"; // Make the drop-down // menu visible } 11 function hideMenu(id){ 12 var ref = document.getElementById(id); 13 ref.style.visibility = "hidden"; // Hide the drop-down menu } </script> <body bgColor="lightblue"> 14 <table width="350" border="2" bgcolor="lightgreen" cellspacing="1" cellpadding="2"> <tr> <td width="100"> 15 <div id="menu" onDblClick="hideMenu('menu');"> 16 <a class="menu" href="#"> US </a><br> <a class="menu" href="#"> World </a><br> <a class="menu" href="#"> Local </a><br> </div> 17 <a href="#" onClick="showMenu('menu');">News</a> </td> <td width="100"> 18 <div id="menu2" onDblClick="hideMenu('menu2');"> 19 <a class="menu" href="#"> Basketball </a><br> <a class="menu" href="#"> Football </a><br> <a class="menu" href="#>"> Soccer </a><br> </div> 20 <a href="#" onClick="showMenu('menu2');">Sports</a> </td> <td width="100"> 21 <div id="menu3" onDblClick="hideMenu('menu3');"> <a class="menu" href="#"> Movies </a><br> <a class="menu" href="#"> Plays </a><br> <a class="menu" href="#>"> DVD's </a><br> </div> <a href="#" onClick="showMenu('menu3');">Entertainment</a> </td> 22 </tr></table> </body> </html>

EXPLANATION

  1. The a selector is followed by the style definition for the links that appear in the main menu.

  2. An ID selector and a class are defined. This style will be used on links in the drop-down menus.

  3. This ID selector defines the style of the first drop-down menu. When the user clicks the News link, this yellow drop-down menu will appear directly under the table cell containing the News link.

  4. Initially, the first drop-down menu is hidden from view.

  5. This ID selector defines the style of the second drop-down menu. It will be orange and drop down directly under the Sports link.

  6. This ID selector defines the style of the third drop-down menu. It will be pink and drop down directly under the Entertainment link.

  7. The CSS ends here, and the JavaScript program begins on the next line.

  8. A function called showMenu is defined. Its only parameter is the id attribute of a div object, that is, the ID of one of the three drop-down menus.

  9. The getElementById() method returns a reference to the div object which contains the drop-down menu.

  10. The visibility property is set to visible . The drop-down object comes into view, right below the main menu item where the user clicked on the link.

  11. A function called hideMenu() is defined. Its only parameter is the id attribute of a div object. When this function is invoked, the drop-down menu being referenced will be hidden from view.

  12. The getElementById() method returns a reference to the div object that contains the drop-down menu.

  13. The visibility property is set to hidden . The object being referenced disappears from view.

  14. An HTML table is defined. It will be light green, 350 pixels wide, and contain one row and three data cells .

  15. The first cell of the table contains a <div> container that is positioned and styled by the CSS #menu ID selector. If the user double-clicks from within this tag, it will be hidden from view.

  16. The links within the <div> container are described by the CSS . menu class. The links are deactivated for this example.

  17. When the user clicks on this link, the main link for the cell, called News, the onClick event will be triggered. A function called showMenu will be invoked, causing the drop-down menu to appear.

  18. The second drop-down menu is created and will be made visible when the user clicks on the Sports link.

  19. The drop-down menu is defined here.

  20. When the user clicks on the Sports link, the onClick event handler will cause a drop-down menu to be made visible.

  21. Like the other two links, the Entertainment link also has a drop-down menu associated with it which will be made visible when the user clicks on it, and made invisible when the user double-clicks on the drop-down list.

  22. The table row and table are closed. See Figure 15.37.

    Figure 15.37. The first drop-down menu off the main menu ”if the user double-clicks his mouse anywhere on the drop-down menu, it will be hidden from view (top); the second drop-down menu (middle); the third drop-down menu (bottom).

Tool Tips

When a user's mouse rolls over a section of text or an image, a little tool tip might appear as a little rectangular box of text to give helpful hints or clues to clarify the presentation. And when he moves his mouse away from the area, the tool tip will disappear. You can use the HTML title attribute to create simple tool tips, or you can create your own by taking advantage of the CSS visibility property and JavaScript event handlers.

Example 15.33

<html><head><title>A tool tip</title> <style type="text/css"> 1 #divclass { font-size:12pt; font-family: arial; font-weight: bold; background-color:aqua; border:thin solid; width: 210px; height:40px; 2 visibility: hidden; /* Can't see the container */ position:absolute; top: 50px; left: 175px; 3 z-index: 1; /* Put the div container on top */ } 4 a { font-family: cursive; font-size: 18pt; font-weight: bold; color:white; position: absolute; left: 60px; } 5 img { position:absolute; top: 50px; z-index:0; } </style> <script language = "JavaScript"> var div1; 6 function init(){ div1=document.getElementById("divclass"); } 7 function showHideTip(e) { 8 if(e.type == "mouseover") div1.style.visibility="visible"; 9 else if(e.type == "mouseout"){ div1.style.visibility="hidden"; } } </script> </head> 10 <body bgcolor=black onLoad="init() ;"> 11 <a href="http://www.servant.xxx" 12 onMouseover="showHideTip(event);" 13 onMouseout="showHideTip(event);" >At Your Service! </a> <br> 13 <img src="waiter.gif"> 14 <div id="divclass">Always tip me at least 20%!</div> </body> </html>

EXPLANATION

  1. A CSS style is defined for the ID selector, #divclass .

  2. The visibility property for this style is set to hidden ; it will not be seen.

  3. The z-index property is set to 1, putting above the image which is set to z-index 0. Remember, the higher the z-index number, the higher the element is placed on the stack.

  4. The style for a link is defined.

  5. A style for positioning an image is defined. Its z-index is 0, placing it below any other elements.

  6. The init() function is defined to get the ID of a div element. In this example, this will be the ID for the tool tip.

  7. The showHideTip() function is defined. It takes one parameter, a reference to an event object. It contains information about the event that caused this function to be called.

  8. If the event was caused by the mouse going over the link, a mouseOver event, then the tool tip will be made visible.

  9. If the event was caused by the mouse moving away from the link, a mouseOut event, then the tool tip will be hidden from view.

  10. As soon as the document has finished loading, the onLoad event is triggered, and the init() function invoked.

  11. This is the link that displays as "At Your Service!". Rolling the mouse over it will cause the tool tip to appear.

  12. The onMouseOver event is triggered when the user puts his mouse on the link. The tool tip will be shown.

  13. When the user moves his mouse away from the link, the tool tip disappears.

  14. The image for the waiter is below the tool tip, because its z-index is 0, whereas the tool tip's z-index is 1.

  15. The <div> container is used to hold the tool tip text and style defined by the CSS ID selector called divclass . The output is shown in Figure 15.38.

    Figure 15.38. Before the mouse moves over the link (left), and after (right).

15.4.8 Simple Animation

Animation on a Web page can be either captivating and attractive or just plain annoying. It all depends on the design. Whether you are creating banners, slide shows, or animated logos, buttons , or icons, they are attention getters. With dynamic HTML you can create your own animations. There are a number of programs available for this, such as Macromedia Fireworks, Stone Design's GIFfun for Mac OS X, and Adobe Photoshop.

The following example takes four GIF images and with the help of a timer, rapidly displays an increasingly smaller image on different positions of the screen, giving the sensation of simple animation ”a green balloon rising into the sky.

Example 15.34

<html><head><title>balloon</title> <script language="JavaScript"> var position, up, upper, uppermost, upperupmost; function init(){ 1 var position = 1; 2 var up = new Image(); up.src="greenballoon.gif"; 3 var upper = new Image(); upper.src="greenballoon2.gif"; var uppermost = new Image(); uppermost.src="greenballoon3.gif"; var upperupmost=new Image(); upperupmost.src="greenballoon4.gif"; ball = document.getElementById("balloon"); } 4 function move() { 5 if ( position == 1){ document.balloonimg.src=up.src; ball.balloon.style.left = 50; ball.balloon.style.top = 200; 6 position = 2; } 7 else if (position == 2){ document.balloonimg.src=upper.src; ball.style.left = 100; ball.style.top = 150; position = 3; } } else if (position == 3){ document.balloonimg.src=uppermost.src; ball.style.left = 150; ball.style.top = 100; position = 4; } else if (position == 4){ document.balloonimg.src=upperupmost.src; ball.style.left = 200; ball.style.top = 10; position = 1; } } </script> </head> 7 <body bgColor="silver" onLoad="init();"> 8 <span id="balloon" > <img name="balloonimg" src="greenballoon.gif" > </span> <form> <input type="button" name="move" value=" Move " 9 onClick="startMove=setInterval('move()',900);"> <input type="button" name="stop" value=" Stop " onClick="clearInterval(startMove);"> 10 </form> </body> </html>

EXPLANATION

  1. The variable position will be assigned 1. This will be the image of the first balloon to be placed on the screen after the user calls the move() function below.

  2. A reference to an image object is assigned to variable, up . The source for the image is a file named greenballoon.gif .

  3. Another image object is created. Its source file is greenballoon2.gif . Each balloon image is scaled down in size.

  4. The move() function is defined. Its purpose is to place, in rapid intervals, the balloon images in different sections of the screen to give the illusion of movement.

  5. With position 1, the first image ( greenballoon.gif ) is positioned at the left bottom part of the screen. The value of the position is set to 2. When the timer calls the move() function, (approximately 1 second from now), the position value is 2 and control goes to line 5.

  6. Position 2 puts the balloon greenballoon2.gif in the middle of the screen.

  7. After the document has been loaded, the onLoad event is triggered and the init() function will be invoked to initialize variables and get a reference to the balloon object.

  8. The <span> tag creates the position of the initial image 10 pixels from the left-hand side of the screen and 250 pixels from the top.

  9. When the Move button is clicked, the onClick event is triggered and the setInterval() method will start calling the move() function every 900 milliseconds. The balloon appears to move from the left to the right, and upward on the screen, getting smaller as it goes to indicate distance.

  10. When the Stop button is clicked, the setInterval() timer is turned off. The output is shown in Figure 15.39.

    Figure 15.39. When the user clicks the Move button, the balloon image changes every second (top); Up, up, and away in my little green balloon... (bottom row).

Категории