User:Moncur/13
13. Using the W3C DOM
[wax ka badal]The DOM and Dynamic HTML
[wax ka badal]Due to the basic DOM of older browsers, JavaScript could only have a limited effect on a page. There were certain elements, such as forms and images, that you could control with JavaScript, but if you wanted to do something more complex—such as adding or removing several paragraphs, making a form appear out of nowhere, or displaying data dynamically within text—you were out of luck.
To escape this limitation, browser manufacturers created Dynamic HTML, or DHTML—an extended DOM that allowed JavaScript to manipulate more of a page. Unfortunately, this was still limiting—you had to work with certain defined parts of the page called layers rather than having complete control over the page.
Worse yet, Microsoft and Netscape created completely different and incompatible versions of DHTML, which led to some complicated and unreliable scripting.
Fortunately, you won't have to learn about those incompatible versions of DHTML because the W3C DOM has made them unnecessary. Although browsers still aren't perfectly interchangeable, today's browsers support enough of the standard DOM to enable you to fully control the content of pages without much concern over browser issues. In this hour and the next hour, you'll create several examples of DOM scripts that will work fine in all modern browsers.
- By the Way
- There are still browser issues, of course. [Hour 15], "Unobtrusive Scripting," will show you how to deal with browser differences and how to minimize your chances of running into problems with new browsers.
Understanding DOM Structure
[wax ka badal]In [Hour 4], "Working with the Document Object Model (DOM)," you learned about how some of the most important DOM objects are organized: The window object contains the document object, and so on. Although these objects were the only ones available in older browsers, the new DOM adds objects under the document object for every element of a page.
To better understand this concept, let's look at the simple HTML document in [Listing 13.1]. This document has the usual <head> and <body> sections, a heading, and a single paragraph of text.
- Listing 13.1. A Simple HTML Document
<html> <head> <title>A simple HTML Document</title> </head> <body> <h1>This is a Heading</h1> <p>This is a paragraph</p> </body> </html>
Like all HTML documents, this one is composed of various containers and their contents. The <html> tags form a container that includes the entire document, the <body> tags contain the body of the page, and so on.
In the DOM, each container within the page and its contents are represented by an object. The objects are organized into a tree-like structure, with the document object itself at the root of the tree, and individual elements such as the heading and paragraph of text at the leaves of the tree. [Figure 13.1] shows a diagram of these relationships.
In the following sections, you will examine the structure of the DOM more closely.
- By the Way
- Don't worry if this tree structure confuses you; you can do almost anything by simply assigning IDs to elements and referring to them. This is the method used in earlier hours of this book, as well as in the Try It Yourself section of this hour. In [Hour 14], "Using Advanced DOM Features," you will look at more complicated examples that require you to understand the way objects are organized in the DOM.
Nodes
[wax ka badal]Each container or element in the document is called a node in the DOM. In the example in [Figure 13.1], each of the objects in boxes is a node, and the lines represent the relationships between the nodes.
You will often need to refer to individual nodes in scripts. You can do this by assigning an ID, or by navigating the tree using the relationships between the nodes.
Parents and Children
[wax ka badal]As you learned earlier in this book, each JavaScript object can have a parent—an object that contains it—and can also have children—objects that it contains. The DOM uses the same terminology.
In [Figure 13.1], the document object is the parent object for the remaining objects, and does not have a parent itself. The html object is the parent of the head and body objects, and the h1 and p objects are children of the body object.
Text nodes work a bit differently. The actual text in the paragraph is a node in itself, and is a child of the p object. Similarly, the text within the <h1> tags is a child of the h1 object.
- By the Way
- In [Hour 14], you will learn methods of referring to objects by their parent and child relationships, as well as ways of adding and removing nodes from the document.
Siblings
[wax ka badal]The DOM also uses another term for organization of objects: siblings. As you might expect, this refers to objects that have the same parent—in other words, objects at the same level in the DOM object tree.
In [Figure 13.1], the h1 and p objects are siblings: Both are children of the body object. Similarly, the head and body objects are siblings under the html object.
Creating Positionable Elements (Layers)
[wax ka badal]Using the W3C DOM, you can control any element in a web page, such as a paragraph or an image. You can change an element's style, as you learned in the previous hour. You can also use the DOM to change the position, visibility, and other attributes of the element.
Before the W3C DOM and CSS2 standards, you could only reposition layers, special groups of elements defined with a proprietary tag. Although you can now position any element, it's still useful to work with groups of elements in many cases.
You can effectively create a layer, or a group of HTML objects that can be controlled as a group, using the <div> or <span> tags.
- By the Way
- The <div> and <span> tags are part of the HTML 3.0 standard. <span> defines an arbitrary section of the HTML document, and does not specify any formatting for the text it contains. <div> is similar, but includes a line break before and after its contents.
To create a layer with <div>, enclose the content of the layer between the two division tags and specify the layer's properties in the style attribute of the <div> tag. Here's a simple example:
<div id="layer1" style="position:absolute; left:100; top:100"> <p>This is the content of the layer.</p>
This code defines a layer with the name layer1. This is a moveable layer positioned 100 pixels down and 100 pixels to the right of the upper-left corner of the browser window. You'll learn more details about the positioning properties in the next section.
- Did you Know?
- As with all CSS properties, you can specify the position property and other layer properties in a <style> block, in an external style sheet, or in the style attribute of an HTML tag. You can also control these properties using JavaScript, as described later in this hour.
Setting Object Position and Size
[wax ka badal]You can use various properties in the style attribute of the tag when you define a layer to set its position, visibility, and other features. The following properties control the object's position and size:
- position is the main positioning attribute and can affect the following properties. The position property can have one of three values:
- static defines items that are laid out in normal HTML fashion, and cannot be moved. This is the default.
- absolute specifies that an item will be positioned using coordinates you specify.
- relative defines an item that is offset a certain amount from the static position, where the element would normally have been laid out within the HTML page.
- left and top specify offsets for the position of the item. For absolute positioning, this is relative to the main browser window or a containing item. For relative positioning, it's relative to the usual static position.
- right and bottom are an alternative way to specify the position of the item. You can use these when you need to align the object's right or bottom edge.
- width and height are similar to the standard HTML width and height attributes and specify a width and height for the item.
- z-index specifies how items overlap. Normally indexes start with 1 and go up with each layer added "on top" of the page. By changing this value, you can specify which item is on top.
- By the Way
- Properties such as left and top work in pixels by default. You can also use any of the units described in the previous hour: px, pt, ex, em, or percentages.
Setting Overflow Properties
[wax ka badal]Sometimes the content inside a layer is larger than the size the layer can display. Two properties affect how the layer is displayed in this case:
- overflow indicates whether the content of an element is cut off at the edges of the element, or whether a scroll bar allows viewing the rest of the item. Values include visible to display content outside the element; hidden to hide the clipped content; scroll to display scroll bars; auto to let the browser decide whether to display scroll bars; or inherit to use a parent object's setting.
- clip specifies the clipping rectangle for an item. Only the portion of the item inside this rectangle is displayed. Normally this is the same as the element's dimensions, but you can define an offset inside the element here.
Using Visibility Properties
[wax ka badal]Along with positioning objects, you can use CSS positioning to control whether the objects are visible at all, and how the document is formatted around them. These properties control how objects are displayed:
- display specifies whether an item is displayed in the browser. A value of "none" hides the object. Other values include block to display the object preceded and followed by line breaks, inline to display it without line breaks, and list-item to display it as part of a list.
- visibility specifies whether an item is visible. Values include visible (default), hidden, and inherit. A value of inherit means the item inherits the visibility of any item it appears within (such as a table or a paragraph).
The difference between display and visibility is that objects set to display: none will not be displayed at all, and the page will be laid out as if the element wasn't there. Objects set to visibility: hidden will still be included in the layout of the page, but as empty space.
Setting Background and Border Properties
[wax ka badal]You can use the following properties to set the color and background image for a layer or other object and control whether borders are displayed:
- background-color specifies the color for the background of any text in the layer.
- background-image specifies a background image for any text in the layer.
- border-width sets the width of the border for all four sides. This can be a numeric value or the keywords thin, medium, or thick.
- border-style sets the style of border. Values include none (default), dotted, dashed, solid, double, groove, ridge, inset, or outset.
- border-color sets the color of the border. As with other color properties, this can be a named color such as blue or an RGB color such as #FF03A5.
Controlling Positioning with JavaScript
[wax ka badal]As you learned in the previous hour, you can control the style attributes for an object with the attributes of the object's style property. You can control the positioning attributes listed in the previous section the same way.
Suppose you have created a layer with the following tags:
<div id="layer1" style="position:absolute; left:100; top:100"> <p>This is the content of the layer.</p>
To move this layer up or down within the page using JavaScript, you can change its style.top attribute. For example, the following statements move the layer 100 pixels down from its original position:
var obj = document.getElementById("layer1"); obj.style.top=200;
The document.getElementById() method returns the object corresponding to the layer's tag, and the second statement sets the object's top positioning property to 200. As you learned in the previous hour, you can also combine these two statements:
document.getElementById("layer1").style.top = 200;
This simply sets the style.top property for the layer without assigning a variable to the layer's object. You will use this technique in this hour's Try It Yourself section.
- By the Way
- Some CSS properties, such as text-indent and border-color, have hyphens in their names. When you use these properties in JavaScript, you combine the hyphenated sections and use a capital letter: textIndent and borderColor.
Try It Yourself — Creating a Movable Layer
[wax ka badal]As an example of positioning an element with JavaScript, you can now create an HTML document that defines a layer, and combine it with a script to allow the layer to be moved, hidden, or shown using buttons. [Listing 13.2] shows the HTML document that defines the buttons and the layer.
- Listing 13.2. The HTML Document for the Movable Layer Example
<html> <head> <title>Positioning Elements with JavaScript</title> <script language="javascript" type="text/javascript" src="position.js"> </script> <style> # square { position:absolute; top: 150; left: 100; width: 200; height: 200; border: 2px solid black; padding: 10px; background-color: #E0E0E0; } </style> </head> <body> <h1>Positioning Elements</h1> <hr> <form name="form1"> <input type="button" name="left" value="<- Left" onClick="pos(-1,0);"> <input type="button" name="right" value="Right ->" onClick="pos(1,0);"> <input type="button" name="up" value="Up" onClick="pos(0,-1);"> <input type="button" name="down" value="Down" onClick="pos(0,1);"> <input type="button" name="hide" value="Hide" onClick="hideSquare();"> <input type="button" name="show" value="Show" onClick="showSquare();"> </form> <hr> <div id="square"> <p>This square is an absolutely positioned layer that you can move using the buttons above.</p> </body> </html>
In addition to some basic HTML, this document consists of the following:
- The <script> tag in the header reads a script called position.js, which you will create later in this section.
- The <style> section is a brief style sheet that defines the properties for the movable layer. It sets the position property to absolute to indicate that it can be positioned at an exact location, sets the initial position in the top and left properties, and sets border and background-color properties to make the layer clearly visible.
- The <input> tags within the <form> section define six buttons: four to move the layer left, right, up, or down, and two to control whether it is visible or hidden.
- The section defines the layer itself. The id attribute is set to the value "square". This id is used in the style sheet to refer to the layer, and will also be used in your script.
Type this document (or download it from this book's website) and save it. If you load it into a browser, you should see the buttons and the "square" layer, but the buttons won't do anything yet. The script in [Listing 13.3] adds the action to the HTML.
- Listing 13.3. The Script for the Movable Layer Example
var x=100,y=150; function pos(dx,dy) { if (!document.getElementById) return; x += 10*dx; y += 10*dy; obj = document.getElementById("square"); obj.style.top=y; obj.style.left=x; } function hideSquare() { if (!document.getElementById) return; obj = document.getElementById("square"); obj.style.display="none"; } function showSquare() { if (!document.getElementById) return; obj = document.getElementById("square"); obj.style.display="block"; }
The var statement at the beginning of the script defines two variables, x and y, that will store the current position of the layer. The pos function is called by the event handlers for all four of the movement buttons.
The parameters of the pos() function, dx and dy, tell the script how the layer should move: If dx is negative, a number will be subtracted from x, moving the layer to the left. If dx is positive, a number will be added to x, moving the layer to the right. Similarly, dy indicates whether to move up or down.
The pos() function begins by making sure the getElementById() function is supported, so it won't attempt to run in older browsers. It then multiplies dx and dy by 10 (to make the movement more obvious) and applies them to x and y. Finally, it sets the top and left properties to the new position, moving the layer.
Two more functions, hideSquare() and showsquare(), hide or show the layer by setting its display property to "none" (hidden) or "block" (shown).
To use this script, save it as position.js and then load the HTML document, [Listing 13.2], into your browser. [Figure 13.2] shows this script in action.
- By the Way
- By assigning values to the layer's positioning properties repeatedly rather than at each click of a button, you can produce an animation effect. See [Hour 19], "Using Graphics and Animation," for an example of this technique.
Summary
[wax ka badal]In this hour, you've learned a bit more about the structure of DOM objects that make up a page, how to use HTML and CSS to define a positionable layer, and how you can use positioning properties dynamically with JavaScript.
Layers are only a simple aspect of what you can do to a page with the W3C DOM. In the next hour, you'll learn how to manipulate the DOM tree to add elements, remove elements, and dynamically change the text within a page.
Q&A
[wax ka badal]Q1: What happens when my web page includes multiple HTML documents, such as when frames are used?
A1: In this case, each window or frame has its own document object that stores the elements of the HTML document it contains.
Q2: If the DOM allows any object to be dynamically changed, why does the positioning example need to use tags to define a layer?
A2: The example could just as easily move a heading, or a paragraph. The layer is just a convenient way to group objects and to create a square object with a border.
Q3: Exactly which browsers support positioning elements with the DOM?
A3: Support for the W3C DOM first appeared in Internet Explorer 5.0 and Netscape 5.0, although it was buggy. Current browsers, such as Internet Explorer 6 and 7, Firefox 1.x, and Opera 7 and 8, have solid and consistent DOM support.
Quiz Questions
[wax ka badal]Test your knowledge of the W3C DOM by answering the following questions.
1. Which of the following tags is used to create a layer?
- <layer>
- <div>
- <style>
2.
Which property controls an element's left-to-right position?
- left
- width
- lrpos
3.
Which of the following CSS rules would create a heading that is not currently visible in the page?
- H1 {visibility: invisible;}
- H1 {display: none;}
- H1 {style: invisible;}
Quiz Answers
[wax ka badal]1. b. The <div> tag can be used to create positionable layers.
2. a. The left property controls an element's left-to-right position.
3. b. The none value for the display property makes it invisible. The visibility property could also be used, but its possible values are visible or hidden.
Exercises
[wax ka badal]If you want to gain more experience using the W3C DOM, try the following exercises:
- Modify the positioning example in Listings 13.2 and 13.3 to move the square one pixel at a time rather than ten at a time.
- Modify the positioning example to eliminate the layer and move a paragraph element instead. You will need to move the id attribute to the paragraph.