Que Logo

Chapter 13

The Document Shuffle


In This Chapter


At various times throughout these chapters, the terms "Web page" and "document" are used somewhat interchangeably. At least, I've never made clear if there is any distinction between the two. In this spin 'round the chapter-o-wheel, you're going to look at documents. More specifically, how you can fiddle with documents using JavaScript.
This, then, is the second chapter in which you examine JavaScript practices that interact with the Web page. Previously, you saw how to affect window elements, such as by opening new windows and creating message boxes. Now, you'll define what a document is and learn how to manipulate it; if there's time, I'll also explain how to make no-fail chicken soup from scratch.

Document Defined


In Web parlance, a document is the file of HTML codes that describe a given page. A page is what appears within the browser window. A typical HTML document contains a variety of characteristics, other than the content of the page itself.
These include a background image (often called a background "texture"), background color, foreground color, and the colors of hypertext links. In traditional HTML, these traits are all defined as attributes of the <BODY> tag.
As in the case of the Web browser's window, the document object is also a built-in object of JavaScript. It has its own set of properties and methods, with which you can influence various aspects of the current document. Like your previous tours of duty, this chapter takes you through the properties and methods of the document object and shows you how to use them in everyday life.

Welcome to the Property


The document object has a whole gaggle of properties associated with it. Most of these properties mimic characteristics that may have been defined in HTML tags. But it's far from redundant mimicry; allowing you to access the properties via JavaScript opens up the possibility of changing a document's original characteristics, if you want.
The first property examples that follow illustrate this concept.

bgColor and fgColor


Two of the most basic characteristics of a document are its colors. A document has two main colors: a background color and a foreground color. The background color defines the color of the "page" itself, while the foreground color defines the color of the text that appears on the page.
In documents, colors are specified in what is known as a hexadecimal triplet. Each color specification actually contains three specifications: red, blue, and green. Thus, you define the background color, for instance, by specifying how much red, blue, and green to mix together to yield the final color.
Each color will have a value from 0 to 255: 0 being a complete lack of the color, and 255 being 100 percent of the color. Quick art school lesson: a background color which has 0 red, 0 blue, and 0 green would be black. A color that has 255 red, 255 blue, and 255 green (that's 100 percent of each), would be pure white.
I'm a Human Calculator
<SB>Hexadecimal is a base-16 numbering system, which contains the base values 0-F. That is, beyond 9 comes A, B, C, D, E, and F. Your common decimal system uses base-10 numbering, which only has the base values 0-9. Converting a decimal number, which you're used to, to a hexadecimal number, requires some addition and multiplication.
In this chapter, you're only considering 2-digit hexadecimal numbers which represent red, green, or blue values (although in decimal, these same values would be 3 digits long, since decimal has fewer possible values for one digit to hold). To convert a hexadecimal number to decimal, use the following formula:

(lefthand hexadecimal digit * 16) + (righthand hexadecimal digit)
Note that a hex. digit of A = 10, B = 11, etc., to F = 15

What?? Consider the hexadecimal value 05

(0 * 16) + (5) = decimal value of 5

Okay, that one was easy. Consider the hexadecimal value 1A

(1 * 16) + (10) = decimal value of 26

Another example: hexadecimal value C5

(12 * 16) + (5) = 197

Finally, the maximum 2-digit hex value: FF

(15 * 16) + (15) = 255

This should give you enough knowledge to guesstimate hex values for the color specification--from there, you can fiddle with the exact values to create the exact color you're looking for.
The above explains the "triplet" part of "hexadecimal triplet." Now let's explain the "hexademical" part. See, JavaScript doesn't like "normal" numbers such as 255. It prefers a different numbering system, known as hexadecimal. The system we humans commonly use is known as decimal. Many computer programs can convert decimal numbers to hexadecimal for you, but for a brief tutorial, see the "I'm a Human Calculator" sidebar.
The value of document.bgColor is the hexadecimal triplet that defines the current page's background color. A possible value would be "000000", or pure black. Note that the long hexadecimal number is, in fact, three 2-digit hexadecimal numbers in a row. The leftmost two digits represent the Red value, the second two represent Green, and the rightmost two represent Blue. Another possible value would be "FFFFFF", or pure white. "FF0000" would be pure red. You can, in turn, alter the current background color by assigning a new hexadecimal triplet to document.bgColor. For example, regardless of what the current page's background color is, the JavaScript assignment

document.bgColor = "#00FF00"

changes the background to pure green. Note the hash mark (#) in the above assignment. It is traditional to place the hash mark in front of a hexadecimal number. If you leave it out of the assignment, it will still work, but note that if you retrieve the value of document.bgColor, it will contain a hash mark preceding the hexadecimal triplet regardless of whether you included it or not.
Along these same lines, document.fgColor will contain the hexadecimal triplet that represents the text color. And, similarly, assigning a new value to this property will change the text color.
Manipulating all of these possible combinations is a pain. Although this is the only way to fine-tune the exact color you will use, JavaScript does provide a shortcut. Instead of the hexadecimal triplet, you can assign a string literal specifying one of JavaScript's built-in color names. JavaScript has a long list of predefined colors, such as "aliceblue" and "crimson" and "palegreen". Check the Appendix at the end of this book for the full list. Simply, rather than an assignment such as

document.bgColor="#000000"

you can instead write

document.bgColor="black"

More Colors alinkColor, vlinkColor, and linkColor


You can specify three other colors in a document. Each of these properties functions the same way as the previous two--they simply affect the color of different characteristics of the page.
You can use each of the above in the standard ways for object properties: you may either retrieve the value from or assign a new value to document.alinkColor, document.vlinkColor, and document.linkColor. If you've coded HTML before, you might have noticed that you can set these same colors in standard HTML tags. So why bother with JavaScript? Because by using JavaScript, you can change the colors in a given page at any time you want-on the fly-perhaps as a result of certain user events. In HTML, you can define the colors only once for the life of the page.
Again, simply because it's fun, you can define the above colors in hexadecimal triplets, or you can use any of the available predefined string literals.

The title Property


The property document.title holds the value of the title of the document as defined in the HTML tags <TITLE> </TITLE>. The title is what appears in the browser window's upper border, and in the bookmark list if the page is bookmarked by a user. The title does not actually appear within the content of the page itself.
As usual, you can retrieve the document's title from this property, or assign a new title to the document via this property.

The anchors Property


An anchor is a spot in a page that has been marked with a "name" within the HTML code. Links can then point to anchors, to send a user to specific locations within a single page. Anchors are defined in HTML with the <A NAME=> tag.
The document.anchors property is an array-that is, an object in and of itself-that contains the value of each anchor on the page, in the order in which they were defined in the HTML code. Let's imagine your page has five anchors defined within it. In that case, there are five properties in the object document.anchors:

document.anchors[0]
document.anchors[1]
...
document.anchors[5]

Each of the above contains the name of the anchor corresponding to the order in which it was defined. So, if you named and defined your anchors in the order Monday, Tuesday, Wednesday, Thursday, Friday, then each of those would be the values contained in document.anchors[0] to document.anchors[5], respectively.
You may use the property length, as in document.anchors.length to retrieve the total number of anchors defined.
Note that you would not use an assignment to document.anchors to bring the user to an anchor within the document. That could be done several ways in JavaScript. Remember that an anchor is specified in a URL with a hash mark following the pathname. Thus, you could assign the entire URL with a hash mark and desired anchor name to location.href. Or, if the desired anchor is within the same page as your JavaScript program, you might simply assign the anchor name to location.hash.

The links Property


In the same spirit as the anchors property, you have the links property. Most pages contain several link definitions throughout the HTML code, as created by the <A HREF=> tag.
document.links is another object array that contains each of the links specified in the current page. Similar to document.anchors, for as many links as there are in the page, there are properties of document.links, in the following manner:

document.links[0]
document.links[1]
...etc.

You can retrieve the total number of links in the document using the property document.links.length. As usual, you can change the value of a particular link by assigning a new string to one of the above properties, as in document.links[2] = "http://www.yahoo.com".
Imagine a scenario where this reassignment may be useful. Imagine that you have a link in the page that-on-screen-reads "Click here to continue". Perhaps, though, you would like that link to take some users to one URL, but other users to a different URL, depending on some other condition-perhaps depending on whether they've purchased more than a certain quantity of mugs.
Thus, you can use an if...else statement to evaluate the user's mug purchase, and on each condition assign a different URL specification to the above link. This would be transparent to the user, as he would simply click on the link labeled "Click here to continue", yet he'd be taken to an appropriate page as determined by your JavaScript program. This is exactly the same code as in the similar example from Chapter 11--except where you sent the user automatically to a new page in that example by using a location.href assignment, here you would replace that with a document.links[n] assignment.

Some Miscellaneous Properties


A few properties aren't of vital consequence, and don't require particularly detailed explanation. Each is relatively straightforward and may not find tremendous usage in your JavaScript programs. However, they're nice to know, especially when you get into those typical JavaScript arguments with friends and colleagues.

The lastModified Property


This property simply contains a string value reflecting the date that the document was last modified. A function might use this property, for instance, to communicate to the user how "fresh" the current page is, in case some of its information may be liable to become out of date.

The referrer Property


This property contains the URL of the page that led to the current page. That is, if the user reached the current page via a link from another page, this property contains the URL of the page that linked them here. You might consider using this property to track statistics about which previous sites users are jumping to yours from.

The location Property


Lastly, this highly redundant property contains the full URL of the current page. Yes, it's the equivalent of location.href.

Forms


Just as for anchors and links, the document object contains an array of properties for each form defined in the document. However, there's more to forms than simply a value, as was the case for anchors and links. Therefore, you will learn about forms in depth in their own chapter, 14.

Methods to This Madness


In fact, there are five methods to this madness called the document object. The methods of the document object are, fortunately, relatively straightforward and useful.

The clear() Method


It shouldn't take the Amazing Kreskin to deduce the function of the document.clear() method. Once called, it clears the contents of the current window. Note that this doesn't affect the actual contents of the document, as defined in the HTML tags. Nor does the clear() method clear any variable values, or anything else. It is purely cosmetic--it merely clears the display window. Of course, you may not want to clear the window unless you plan to display further text in it. Fortunately, there are two methods for doing just that.

write() and writeln()


You can use both of these methods to output HTML to the current window. As the parameter to either method, you pass on a string that contains the HTML code that contains what you want sent to the window.
For example, suppose you want the string "Thank you for ordering" written in the window in large type. The HTML <H1></H1> tag is one way to generate text in a large font size. Therefore, you could simply use the method call

document.write ("<H1>Thank you for ordering!</H1>")

Alternatively, you might have constructed a string somewhere else in your JavaScript code and assigned that to a variable, such as phrase. In this case, you can simply pass the variable phrase as the parameter to the method call:

document.write (phrase)

The difference between write() and writeln() is that the writeln() appends a newline character to the end of the output. A newline character is basically like a carriage return. However, keep in mind that these methods output their parameters as HTML. And, remember that HTML ignores newline characters when it comes to outputting to the screen.
What does the above mean? It means that HTML does not insert line breaks in screen output unless you specify a line break using either the <BR> or <P> tags. Any "natural" line breaks in your HTML code, such as from hitting return, are ignored. The only time this is not true (and carriage returns are honored) is for text that resides between <PRE> </PRE> tags. Those tags define a section of text that is "preformatted," and it appears on-screen in the browser's defined monospace font (often Courier). (Remember that a monospace font is one in which all characters have equal width.)
Thus, in most cases, there will be no effective difference between the write() and writeln() methods, unless your string parameter contains HTML code that places the output within <PRE> </PRE> tags.

Bonus Events


It so happens that the document object also has two relevant event triggers worth mentioning: onLoad and onUnload.

The onLoad Event


Watch Your HEAD
The <BODY> tag occurs very early on in the HTML document. This highlights the need to define your functions as early on in the document as possible--specifically, within the <HEAD> </HEAD> section, which is one of the only places you have an opportunity to do so prior to the <BODY> tag.
You can use this event trigger to launch a particular JavaScript program or function upon the completion of initially loading the document. Perhaps you coded a JavaScript function that displays an alert message to the user before he even begins reading the page. The onLoad event would be useful for this purpose.
You include the event as an attribute of the document's <BODY> tag, as in

<BODY onLoad="welcome()">

In this example, the onLoad event handler is set to call the function welcome(), which performs some feat of programming, such as popping up an alert window that requires the user to read an important disclaimer before he begins looking at the page. (Users will likely find this very annoying, but you could program it.)

The onUnload Event


This event is triggered when the user "unloads" or exits the document. It, as well, would be defined as an attribute of the <BODY> tag. You might, for example, use this to show a message to the user after he chooses to leave your page, such as by calling a function that writes the text "You come back now, you hear?" into the document window.

<BODY onLoad="welcome()" onUnload="bye()">

As it stands, the only major aspect of JavaScript remaining to be covered is the forms objects. And--wouldn't you know--I have it covered. Next chapter in fact, so don't stop reading here. This is like the last 50 steps in an 8K run… just a few more properties… maybe a method or two… you're almost there.

The Least You Need To Know


Previous Chapter Next Chapter



Beginning of ChapterTable of ContentsBook Home PageQue Home Page


For comments or technical support for our books and software, select Talk to Us.
To order books, call us at 800-716-0044 or 317-228-4366.
© 1996, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon & Schuster Company.