Manipulating The Browser
In order to make use of JavaScript, you must have something to manipulate. Fortunately, both of the major browsers expose a number of pre-built objects that you can use to control and interact with the the browser. The sum of these objects is called the Browser Object Model. Unfortunately, however, each major browser exposes objects a little differently. This can make your life as a web programmer unpleasant to say the least. For now, we'll concentrate on those objects that both major browsers provide access to in more or less the same way. Later, when we explore Dynamic HTML, we'll need to take into account the differing object models to insure success on both major browsers.
The Browser Object Hierarchy
The browser object hierarchy is nothing more than an object tree composed of objects that are pre-built for you. You access any of the objects by traversing the tree using the dot notation. At the base of the tree is the window object. All of the other objects are accessed by following a path to them. Below is a diagram of the browser object model:
window | |||||||||
| | |||||||||
document | --------- | history | --------- | location | |||||
| | |||||||||
anchor | link | image | form | ||||||
| | |||||||||
button | checkbox | radio | textarea | password | reset | select | submit | text | hidden |
In order to gain access to the value of a text field named "text1" on a form called "myForm", you must refer to the text field by traversing the tree:
window.document.mailForm.text1.value
In essence, the value is the leaf on the tree. You start at the trunk, and gradually work your way up the branches until you finally get to the leaf. Simple! In fact, since JavaScripts always apply to the current window (that is, their scope is the current window) you can omit the window reference altogether:
document.mailForm.text1.value
As shown in the above diagram, all web pages contain the window, document, history, and location objects. There is another object that all pages share called the navigator object that holds information about the browser itself. You don't really have much control over this object. We will find, however, later on, that knowing which browser your user is surfing with can be a valuable piece of information.
The window Object
The web browser creates at least one window object for every page. It can be confusing when you consider that each page has a document object as well. But if you think of the window as the actual window and the document as the contents of the window, you'll be happier in the long run. Following is a table of the window object's properties:
Property | Description |
closed | Determines if a window has been closed (Boolean) |
defaultStatus | The default status bar message (String) |
length | The number of frames in the current window (Integer) |
name | The name of the window (String) |
opener | A reference to the window that opened the current window by using window.open() (String) |
parent | Refers to the window that contains a frameset (object) |
self or top | The current window (object) |
status | The current message displayed in the status bar (String) |
document | The current contents of the window (object) |
location | The current URL of the window (object) |
history | The history list of the browser session (object) |
Next is a table displaying the methods of the window object:
Method | Description |
alert(String) | Displays a JavaScript alert message (Modal) |
blur() | Removes the focus from the window |
clearTimeout(timerID) | Clears the timer function with the specified timerID |
close() | Closes the specified window |
confirm(String) | Displays a message box with OK and Cancel buttons. Returns true if OK is pressed, false if cancel is pressed (Modal) |
eval(String) | Evaluates the argument as JavaScript code and returns the results |
focus() | Places focus on the specified window |
open(args) | Opens a new window based on args (More a little later!) |
prompt(String,default) | Opens a prompt box with the string argument as the prompt. If default is specified it is shown as the default value of the prompt box |
scroll(x,y) | Scrolls the window to the given x,y coordinates |
setTimeout(code,ms) | Evaluates the code argument after the specified number of milliseconds. Returns a timerID that can be used by clearTimeout() |
The window object can respond to the following events:
Event | Triggered When... |
onBlur | the focus is removed from the window |
onError | an error occurs on the window |
onFocus | the focus is applied to the window |
onLoad | when the browser finishes loading the document into the window |
onUnload | when the user exits from the document in the window |
You can attach events to the window object by including them inside the <body> or <frameset> elements of your pages:
<body onLoad="alert('Finished!')">
Controlling Windows
The window.open() method deserves some special attention as it can be very powerful. The open() method takes a number of arguments:
URL | The URL of the page to load into the new window | ||||||||||||||||||||||||
name | The HTML target name of the new window | ||||||||||||||||||||||||
properties | A comma separated list of properties for the new window:
|
You can specify what to include when you open a new window by iterating through the arguments and then the properties like this:
window.open('somePage.htm','myWindow', 'toolbar=no, menubar=no, width=200,height=300,scrollbars=yes');
This code opens a new window with a target name of myWindow and displays the somePage.htm document. In addition, the window is 200 pixels wide by 300 tall, shows no toolbar or menu, but displays scrollbars if necessary. Pretty cool.
Where do I put my scripts?
That's an interesting question. Where should scripts go on a web page? Well, the short answer is, of course, exactly where they belong! In other words, scripts can appear anywhere on your page and they will get executed in the order in which they are received. Many programmers choose to place their scripts in the <head> of their web pages as that section always gets processed first. That's generally good practice but isn't always the case. Let's try a simple example. Try entering this code:
<html>
<head>
<title>Windows Example</title>
<script language="JavaScript">
<!--
newWindow = window.open("http://www.bright-moments.com", "myWindow",
"toolbar=no, menubar=no, height=480, width=640, status=no");
//-->
</script>
</head>
<body>
</body>
</html>
Running this simple html page through the browser results in a number of things. First, a new window object is created with the name newWindow. The name is important if you want to reference the window later in code (otherwise, it can be omitted). Second, the newWindow object opens the URL specified in the first argument - in this case the bright-moments website. Third, the window is given a target name so that links from the page that opened the window can target the newWindow. This is different than the name property as name is a JavaScript object property and has nothing to do with the HTML target attribute. Fourth, the properties of the newWindow are determined by the third argument. In this case, the window will be 640 pixels wide by 480 tall, and contain no toolbar, menubar, or scrollbars. Finally, this code implicitly assigns the opener property to the window that opened the newWindow - namely, the window with our script on it. That's a lot of stuff going on in one short line of code!
We can take this premise a step further by creating a remote control for any web site. The idea is simple: open a new window with your navigation structure on it, and make use of the opener property to access the JavaScript objects on the page that opened the window. Remote controls are everywhere these days. Why not create one for your web site!?!
Let's try a remote control example to see if we can make this a little clearer. Along the way, we'll learn how to apply the javascript: pseudo-protocol to elements on a web page. We'll also write a generic function to handle opening locations on our opener page on demand. This concept can use buttons, images, or even plain text to accomplish our goal. First, let's design the page we'll use for our remote. Type in the following in a new document:
<html>
<head>
<title>Information Remote Control</title>
</head>
<script language="JavaScript">
function go(url){
window.opener.location.href=url;
}
</script>
<body>
<p>At your fingertips</p>
<p><a href="javascript:go('http://www.cnn.com')">
<img border="0" src="http://www.bright-moments.com/webdeveloper/images/cnn.gif" width="100" height="24"></a></p>
<p><a href="javascript:go('http://www.msnbc.com')">
<img border="0" src="http://www.bright-moments.com/webdeveloper/images/msnbc.gif" width="100" height="62"></a></p>
<p><a href="javascript:go('http://www.cnnsi.com')">
<img border="0" src="http://www.bright-moments.com/webdeveloper/images/cnnsi.gif" width="100" height="31"></a></p>
<p><a href="javascript:go('http://www.espn.com')">
<img border="0" src="http://www.bright-moments.com/webdeveloper/images/espn.gif" width="100" height="34"></a></p>
</body>
</html>
Save the file as remote.htm. This is the file that we will open when our main page loads. There are a couple of things to notice about this file. First, notice the generic function go() in the head. This function essentially tells the opener to load the specified url. You may specify any valid url for the argument and you can be relatively sure that the given url will be displayed in the window that opened the remote. Second, notice the href attribute for all our links. It uses the javascript: pseudo-protocol (pseudo because it's not really a protocol like http or ftp) to run the go() function and passes on a url appropriate for each of the images.
Now, let's create the main window:
<html>
<head>
<title>Information At Your Fingertips!</title>
</head>
<script language="JavaScript">
function showRC(){
rc = window.open('remote.htm','rc','width=140,height=300');
}
</script>
<body onLoad="showRC()">
<p>Information at your fingertips. Click on a link on the remote control to open it in this window!</p>
</body>
</html>
Save this file as info.htm in the same directory as remote.htm (we used a relative path in the showRC() method). In this file, we've chosen to open the remote control window in the window's onLoad event. In the <body> element, we've captured the onLoad event and told the browser to execute the showRC() function. This causes the browser to open our new remote control window, and assigns itself to the new window's opener property. When you click on a link in the remote, the page gets loaded in the opener. One last thing: notice that we didn't specify to explicitly disable the window's toolbar, menubar, and status bar. Instead, we took advantage of the fact that these properties are automatically set to 'no' if they aren't specified. Be warned though. If you take this a step further, and don't specify a width and height, the result is a default browser window with all of the accoutrements. Pretty cool! You can see this file in action on the Source Code page.