Chapter 11
How Much Is That Object in the Window?
In This Chapter
As you've seen, the purpose of JavaScript is to play a role in the workings of a Web page. In Chapters 6-9, you first learned the programming foundations of the JavaScript language itself. Then I ate cookies. In Chapter 10, you saw one way to integrate JavaScript programs in the functionality of a Web page--via event triggers.
Welcome, then, to Chapter 11. You now begin a journey into using JavaScript to interact with and/or control various characteristics of the Web page itself. You'll start at the top, with what is known to programming cognoscenti and exterior decorators alike as "the window."
Imagine launching your Web browser. After some hard drive activity, the browser pops onto the screen, and you are presented with an initial Web page. It is that space on your screen where the Web page appears that is the "window." In fact, your Web browser is mostly one huge window, although it has some navigational controls above the window and perhaps some status information below the window.
Everything that appears within a Web page, therefore, must appear within the window. For this reason, the window is called the "top-level" object. Recall the JavaScript definition of an object, such as the sweater object. Everything about the sweater-material, color, size, and price-is a property of the sweater. In this case, everything about the Web page, from its colors to background image, to form elements, and so on, is a property of the window.
In terms of JavaScript, then, the window is considered an object. When you refer to properties of the window, such as form elements in the previous chapter, you might recall that you have never explicitly written the object window.property. You don't usually need to, because JavaScript can assume that any other object you refer to in a program (such as a form) is necessarily a property of the window object, which is why you haven't done so.
Until now. Some goals you want to accomplish do require you to specify the window object in some way. That's the thrust of this chapter: looking at the window, rather than merely through it.
The window object contains several properties that you might need to reference, along with some nifty examples as your bonus gift. Keep reading.
Look at the bottom of the Netscape window. The small area in the bottom frame of the window will sometimes read "Document: Done."
This is the status line, and the Web browser uses it to report, well, status messages to the person using the browser. In this case, the status message tells you the document has finished loading. You, as a proprietor of JavaScript and knower of the window object can conjure up your own messages to appear on the status line.
The basic template for setting the status message text is
window.status = "messagetext"
The most likely places you would use the status property are in an onEvent trigger or the function that acts as an event handler. To create an example of the latter, you can create a Web page with two buttons on it. Label one "Try me!" and the other "Over here!". When the user clicks on either, the status line will be set to an appropriate message. You'll define a function msg(msgtext) to act as the event handler.
<html><body><head>
<script language="JavaScript">
function msg(msgtext)
{window.status=msgtext}
</script></head>
<form><input type=button value="Try me!" onClick="msg('That was nice')"></form>
<form><input type=button value="Over here!" onClick="msg('Hey there')"></form>
</body></html>
The function accepts a parameter from the onEvent call and assigns that value to window.status. That's the relevant heart of this example. Down below, where you define the form element buttons, you use the traditional onEvent call as discussed in Chapter 10. Note that you pass string literals to the function, and, therefore, enclose them in single quotes.
If you load the above file into your Web browser, you'll see a window with two buttons. Clicking on them brings up their associated status line messages.
Some claim it pretentious to refer to yourself, but in JavaScript you won't be ostracized for doing so. In fact, sometimes, you have good reason to. Technically, self is a synonym for window. Therefore
<C1>self.status = "Wake up!"
is the same as
<C1>window.status = "Wake up!"
However, the JavaScript creators realized a possible conflict. Let's say you created a form element in your page that has the internal name "status" (as defined by the NAME= attribute of the form element tag). In this case, if you ever need to refer to it in a window property construction, it's unclear whether you meant the window status line property or the form named status.
Therefore, you have the option of using self.property in cases where there may be ambiguity. Of course, you needn't program in any ambiguity in the first place when naming your form elements, but just in case, self is there for you.
Frames aren't discussed much in this book, as they are a Netscape HTML invention. In general, we've been avoiding overly complex HTML codes, since this is a book about JavaScript and not HTML. Nonetheless, the two are bedfellows, since they both contribute to a Web page's design and functionality.
If you don't already know how to code frames into HTML, this book isn't the place to learn--but as a reminder, frames are subwindows within the main window of a Web page. Thus, the top-level window of the Web page pictured here contains three frames:
It's quite logical, then, that each frame is a property of the window object. In turn, each frame has its own properties, because each is its own minidocument, and thus possesses the properties that any document would have (Chapter 13 covers all this).
Each frame is referred to as window.frame[0], window.frame[1], and so on. Therefore, as you'll see when we talk about document properties in Chapter 13, the properties within a frame can be described as window.frame[0].property. For now, this is all you need to know, that each frame is a property of the window object.
In the spirit of "many different names for the same thing," you might remember that a method is a function that is part of an object. You coded a method called sweater.price() back in Chapter 9. Thus, the object window also has a set of methods associated with it. You can (and will) use these for a variety of useful purposes; therefore, you will now embark on a guided tour of window object methods.
What better way to let the user know something than by shoving it in his face? Enter the alert. An alert, in general-speak, is one of those message windows that pops up on the screen to tell you something. Usually, it has an "OK" button you click to signal that you've read this urgent message and would like to continue.
Consider the hypothetical example where you requested that the user enter his e-mail address into a form text-entry element. You previously saw how you can use an onSubmit event trigger to check the user's entry for validity before allowing the submission to proceed (in Chapter 10). Let's build on that example. Suppose the submitted address is deemed nonplausible, and you want to pop up an alert telling the user that he is an abject liar.
The format for the alert method is: window.alert ("message")
After the user acknowledges the alert by clicking the "OK" button, JavaScript will move on to the next statement in your code or function. To reprise, your function evalform() was triggered by the following:
<FORM onSubmit="evalform(this.email.value)">
<INPUT NAME=email TYPE="text" ROWS=1 SIZE="20">Enter your e-mail address
<INPUT NAME=submit TYPE="submit">
<INPUT NAME=reset TYPE="reset">
</FORM>
Presumably, then, you have defined the function evalform() earlier in our document, and it might go a little something like this:
function evalform (address)
{ crucial = address.indexOf ("@") ;
//the above uses a method of the string object to locate an at-sign in
//the submitted form
if (crucial == -1)
{ window.alert ("Your e-mail address is invalid! You are an abject liar!") ;
return false }
else
{ return true } ;
}
The preceding function accepts a parameter, which is the submitted e-mail address to validate. The address.indexOf property is a method of the string object (covered in the appendix at the end of this book), which returns the position of the specified character within the string. In this case, you're searching for an @ symbol, because all valid e-mail addresses have this symbol. The position of that symbol is assigned to the variable crucial and will be a value of -1 if the symbol is not found in the string. This will be your only test, because this is simply an example.
Following that, you use a standard if...else clause, wherein if the @ symbol is not located, the window.alert method is called with an appropriate scolding to the user. Also note that the Boolean false is returned, to prevent submission of the form. Lastly, the else clause takes care of the condition where the @ was located, and simply returns a logical true, which allows the submission to proceed.
The confirm() method is another type of message box. If you've ever used a computer-and at this stage of the book, I deeply hope you have-you've seen confirm messages. They typically pose a question or proposition, and you are asked to choose between "OK" or "Cancel."
You would use the confirm() method of the window object thusly:
window.confirm ("message")
This method returns a true value if the user opts for the "OK" option, or a false if "Cancel" is selected. In some cases, then, because a result is returned, you might want to call this method as somevariable = window.confirm ("message"). Next, you add a confirm() method to the e-mail validation function. In this case, if you determine that the address is valid, you repeat it to the user in a confirm message so that he can verify its accuracy.
Simply add the following highlighted code to your evalform() function:
function evalform (address)
{ crucial = address.indexOf ("@") ;
if (crucial == -1)
{ window.alert ("Your e-mail address is invalid! You are an abject liar!") ;
return false }
else
{ message = "You entered " + address + " -- is this correct?";
return window.confirm (message) } ;
}
You've added only two lines to the previous version of this function: both occur in the true (address is valid) condition. First, you create the message to use in the confirm() method. You do this by making a variable message to which you assign three concatenated strings using the string concatenate operator (+). Below that, you call the window.confirm() method with the previously made message, which is what the user will see. Note that you make the method call as part of a return statement-the confirm() method will return a true or false, and you want to pass that result back to the calling form, which will then proceed with or cease the submission.
The prompt() method pops up a nifty message box, into which you may ask the user to input some sort of information. That information is then assigned to the variable to which this method is assigned, to be used as you may want for any other purpose. For this example, consider this scenario: You present a series of form buttons, each one representing an astrological sign. Somewhere in the Web page, the user is told to click whichever sign belongs to him. Upon doing so, you then prompt the user to enter his age.
The prompt() method works as follows:
somevariable = window.prompt ("prompt message" , defaultvalue)
The prompt message represents the proposition you want to put to the user. The defaultvalue represents some data that you'd like to appear in the prompt by default. If you have no preferred default value, just enter two double-quotes in that spot (like this: "").
In this example, you'll validate the age the user enters to be somewhere within the known human lifespan. If it fails this test, a scolding alert will pop up, and then he will be asked to enter his age again. If the entered age passes, the user will be thanked. Note that you don't do anything else with his age in this particular example, but, of course, you may choose to use it for any other programming purpose you like.
Here is the full code of your little programming feat:
<script language="JavaScript">
function getage ()
{ age=window.prompt ("How old are you?","") ;
if ((age<1) || (age>120))
{ window.alert ("Why must you turn this page into a house of lies?") ;
getage () }
else
{ window.alert ("Thank you.") }
}
</script>
<FORM>
<INPUT NAME=gemini TYPE=button value="Gemini" onClick="getage()">
Click your sign</FORM>
Several examples are worth noting in this program. Jump to the final line first, the <FORM> definition. Here, as usual, you define a form element (a button) and include the onClick event trigger. To handle the event, you call the function getage(), which takes no parameters. Standard stuff.
Now up to the function definition itself, at the top of the program. The first statement in the function definition is your prompt() method. It will ask the user "How old are you?" and present her with an entry blank with no default value. Whatever the user enters is assigned to the variable age. You then test age for validity, using an if...else statement. Note the nifty conditional in the if clause, which uses a logical operator (OR) on two comparison operators.
Should the age be deemed invalid (outside the range 1-120), an alert pops up accusing the user of duplicity. Note that after the accusatory alert, the function getage() is then called again. Yes, it calls itself. That will essentially restart the function, thus letting the user start all over with the age prompt.
If age falls within the acceptable range, an alert pops up merely thanking the user for his input, and thus ends the function.
The following is a picture of the prompt method in action:
Finally, at the sunset of your journey into the window object, consider methods that give rise and fall to windows themselves.
You can use the open() method to create an entirely new browser window. That is, the current window remains in place, but a new window is opened on the desktop. The new window is essentially another Web browser, and you define its characteristics--including size, title, document to open, navigation buttons to make available, and so forth--with the open() method.
Why would you use this method? Perhaps in your Web page, you want to show the user an example of something on another web page. Rather than load that example page within your current window-thus eliminating your explanation from the screen-you might open a new adjacent window that contains the example. At the end of the example, the user could then either manually close the new window himself, or choose some "I'm done" button, which would trigger the close() method, thereby closing the new window.
The formats for these methods are
window.open ("UrlToOpen","windowname","feature1,feature2,feature3,etc.")
window.close ()
The window.close() method must be contained in JavaScript code within the window
to be closed. One window can't close another window; a window can only close itself (window suicide). Therefore, using the window.close() method is simple; just include a call to it as the event handler for some element that indicates to the user that he is done with the window, such as a form button.
The window.open() method has a few more parameters, as you can see. The first two parameters are straightforward:
- UrlToOpen is the address of the document you'd like to be opened in that window (for example, http://mydoc.html).
- windowname gives the window an internal name, which may be used for other references. Note, this name doesn't seem to appear anywhere visible on the window itself.
| How Many Pixels in an Inch? |
| Noncomputer nerds might not be used to measuring sizes in pixels. But that is the standard measurement tool for the images on a computer screen. For the purposes of creating your window sizes, use the following guidelines: a standard VGA screen on a 13-14 inch monitor-which is the most common screen size in use-is 640 pixels wide by 480 pixels high. Therefore, determine what percentage of the screen you want your new window to eat up, and use the 640 by 480 scale accordingly. Furthermore, many users use screen sizes of 800 by 600 on 14-15 inch monitors, while those with 17-inch monitors more commonly use 1,024 by 768 pixels. At this point, 640 by 480 is still considered the most common standard size against which to measure your windows. |
Finally, you may provide any, all, or none of the list of possible feature characteristics of the new window. Separate each feature by a comma but not a space, just as presented in the template example for the previous method. The possible features are
| toolbar=yes or no |
Determines whether to include the standard Back, Forward, Home toolbar. |
| location= yes or no |
Determines whether to show the current URL location. |
| directories=yes or no |
Determines whether to show "What's New" "What's Cool," or other buttons. |
| status=yes or no |
Determines whether to have a status bar at the bottom of the window. |
| menubar=yes or no |
Determines whether to include a menu bar at the top of the window. |
| scrollbars=yes or no |
Determines whether to create scroll bars if the document exceeds the window size. |
| resizable=yes or no |
Determines whether the user may resize the window. |
| copyhistory=yes or no |
Determines whether this new window should inherit the current window's session history. |
| width=# pixels |
Defines how wide the window should be, measured in pixels. |
| height=# pixels |
Defines how tall the window should be, measured in pixels. |
Given all of the features previously described, let's create an onEvent trigger, which will create a new window using some of the above features.
<INPUT NAME=newwin TYPE=button value="Click me for a new window" onClick="window.open ''http://mydoc.html','newwin','toolbar=no,status=yes,scrollbars=no, resizable=no,width=320,height=240')">
I know that looks messy, but it's really just a long list of parameters. Note the use of single quotes within the open method call, because of the double quotes that must surround the onClick definition.
| Assume True |
| If you don't specify a window feature in the open() method call, it will default to yes. Therefore, if you want a feature false, be sure to list it and assign it "no" in the open() method call. |
As a certain animated pig who shall remain nameless used to say, "As far as window objects go, that's all folks!" (Well, he said something like that. It was a long time ago.)
- The entire window through which a Web page is viewed is a JavaScript object, known as window.property.
- All elements and characteristics of a Web page are properties of the window object.
- window.status="message" defines the status bar message.
- window.frame[x].property refers to property of frame number x.
- window.alert ("message") is a method that pops up an alert box.
- window.confirm ("message") is a method that pops up a confirmation box; it returns true if user selects OK, and false if the user clicks CANCEL.
- somevariable=window.prompt ("message","defaultvalue") is a method that pops up a prompt box and assigns the user's input to somevariable.
- window.open ("UrlToOpen","windowname","feature1,feature2,etc") launches a new window with feature characteristics.
- window.close() kills the window that uses this method call (window suicide).



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.