Using Variables and Built-in Functions to Update Your Web Pages Automatically - Page 3
Using Variables and Built-in Functions to Update Your Web Pages Automatically
Write Here Right Now: Displaying Results
write() function to write text to a web page. Figure 2-4 shows how to use
write() to let your visitors know how many seconds there are in a day. Figure 2-5 shows the page this code displays.
Figure 2-4: Using write() to write to a web page
Line-by-Line Analysis of Figure 2-4
Line 24 in Figure 2-4 writes the words there are to the web page (only the words between the quote marks appear on the page). Don't worry about all the periods and what
document really mean right now (I'll cover these topics in depth in Chapter 4, when we talk about image swaps). For now, just remember that if you want to write something to a web page, use
window.document.write("whatever");, placing the text you want written to the page between the quotes. If you don't use quotes around your text, as in
seconds_per_day variable, like this:
Any series of characters between quotes is called a string. (You'll be seeing lots of strings throughout this book.) Strings are a basic type of information, like numbers—and like numbers, you can assign them to variables.
To assign a string to a variable, you'd write something like this:
thau! is the string assigned to the variable
You can stick strings together with a plus sign (+), as shown in the bolded section of Figure 2-6. This code demonstrates how to write output to your page using strings.
Figure 2-6: Putting strings together
Line-by-Line Analysis of Figure 2-6Line 26 in Figure 2-6,
assigns the string "there are" to the variable first_part. Line 24,
sets the variable
last_part to the string "seconds in a day." Line 25 glues together the values stored in
last_part. The end result is that the variable
whole_thing includes the whole string you want to print to the page, there are 86400 seconds in a day. The
window.document.write() line then writes
whole_thing to the web page.
Note: The methods shown in Figures 2-4 and 2-6 are equally acceptable ways of writing there are 86400 seconds in a day. However, there are times when storing strings in variables and then assembling them with the plus sign (+) is clearly the best way to go. We'll see a case of this when we finally get to putting the date on a page.