Control Browser Objects with JavaScript

You've mastered HTML. Now move on to JavaScript and take control of your user's browser.

by Chris Barlow

When it comes to manipulating or monitoring a user's browser environment, HTML comes up short due to its lack of programmability. One of the most popular and powerful ways to add logic and programmatic functionality to Web pages is to use JavaScript. If you're getting started with Web development using JavaScript, you'll want to set aside the time to learn all the new tools at your disposal.

 Premier Members: Download the code
for this article

 Registered Members: Download the code
for entire issue

Not a premier member?
Upgrade now!

If you've programmed in any other language, you should be able to quickly pick up JavaScript's syntax. Variables, loops, and conditional statements are much the same from one language to another, but it will take longer to learn the properties and methods of the common objects you'll be using in Web development. Learning how to interact with the browser's object model is a good place to start. You won't need access to a Web server for testing the code we'll use in this column—as long as you can load an HTML file into a browser, you can experiment with that browser's objects.

As you develop a site on the Internet you need to remember that your Web page can be accessed by users all over the world using all kinds of browsers. Some of the browsers may not be compatible with Java-Script. Despite this caveat, the vast majority of users will access your site using some recent flavor of Microsoft Internet Explorer or Netscape Navigator. Although there are some major differences between Navigator and IE (with minor differences between versions of each) the two most recent versions of each browser support most basic JavaScript functionality.

Let's start experimenting with JavaScript. Open Notepad and create a simple HTML test form with two text fields using this code:

<html><head><title>Test Form Page</title>
</head><body>
<h1>Test Form Page</h1>
<form NAME="Form1" METHOD="POST"
   ACTION="javascript:alert(Form1.FName.value 
   + ':' + Form1.Email.value)">
<p>Name:<input TYPE="TEXT" 
   NAME="FName" SIZE="35"><br>
Email:<input TYPE="TEXT" 
   NAME="Email" SIZE="25"> </p>
<p><input TYPE="SUBMIT" VALUE="Submit 
   Form"></p>
</form></body></html>

 
  Figure 1 Simple JavaScript Form Action. By setting a form's Action property to a JavaScript alert statement, you can display a message box to let you know the form has passed the validation and is ready to submit to the Web server for processing.

Note how the form's Action property is set in this example. Usually, a form is submitted to a script file on Web server, but this embedded JavaScript lets you test the form action without a Web server. When the Submit button is clicked, the JavaScript form action simply displays a message box with the contents of the form fields (see Figure 1).

One thing to remember—JavaScript is case-sensitive. If your code looks correct but does not work, check to make sure you have the right case for each letter. In the example above, Fname or fname will not work!

When the browser loads an HTML page, a window object is created. The window object, just like other objects you work with, has a set of properties, methods, and events (see Table 1). Once created, you can use JavaScript code to set or read the properties, call the methods, and respond to the window object's events. For example, you can add an event handler for the onLoad event of the window object which is called when the browser finishes loading the window. To see how this works, replace the second line of code in your test file with these lines of code:

<script LANGUAGE="JavaScript">
function AppDisplay()
{
alert(navigator.appName + "\n" 
   + navigator.appCodeName + "\n"
   + navigator.appVersion);
}
</script>
</head><body onLoad="AppDisplay()">

The last line sets the event handler for the onLoad event to the function AppDisplay. The AppDisplay function uses the alert statement to display a message box showing three properties from the navigator object. Notice the use of the \n escape sequence to place each of the properties on a new line. You can use these properties to identify the browser being used, its version, and the underlying operating system.

For example, you can use this function to check which operating system a visitor uses. If you call this function in the onLoad event of the window, it will detect which operating system is running. The CheckOS function will redirect the browser to another URL if the user is using Windows 95, by using the indexOf method of the AppVersion property to see if it contains "95." It then sets the window object's location property to the new URL:

function CheckOS()
{
if(navigator.appVersion.indexOf("95") != 
   -1)  
   {
   alert("This page not for Windows 95")
   window.location=
      "http://www.microsoft.com";
   }
}

Pulldown menus
JavaScript is also useful for creating more interesting user interface elements in Web pages. A common element of today's Web pages is a pulldown menu that makes navigation easier within the Web site. You can choose from several different locations and, as soon as you make a selection, the browser will jump to that location. By adding a Select control to a form, and adding a JavaScript function to handle the onChange event, you can change the window's location property to any URL. Add this code to your sample form:

<p><input TYPE="SUBMIT" VALUE="Submit 
   Form"></p>
<SELECT NAME="select1" 
   onChange="NavTo(select1)" SIZE=1>
<OPTION SELECTED VALUE=0> --Choose One-- 
<OPTION VALUE="http://www.devx.com">DevX
<OPTION VALUE="http://
   www.vbexpert.com">VBExpert 
<OPTION VALUE="http://
   www.netscape.com">Netscape 
<OPTION VALUE="http://
   www.microsoft.com">Microsoft 
</SELECT> 

Note that the onChange event is handled by the NavTo function, and the Select control is passed to that function as an argument. Go back to the top of your file and add code for the NavTo function, that checks the selectedIndex property of the Select control to make sure it is not zero. Then set the window's location property to the selected option. Because the window object is the default object, it is not necessary to use the window.location syntax:

function NavTo(sel)
{ var myindex=sel.selectedIndex 
if (myindex != 0) { 
   location=sel.options[myindex].value;
   }
}

The window object contains several other objects in the browser's object model hierarchy. One of the most commonly used objects is the document object. The document object has several interesting properties. For example, the domain property specifies the domain name of the server that served the document, and the referrer property is the URL of the calling document. But it is the write method of the document object that gets the most use. For example, rather than displaying the name and e-mail address from your test form in a message box, you could use the open method of the window object to create a new window. Then, use the write method of the new window's document object to write in some HTML. First, change the Action property of your test form to call a ShowFields function and pass the form as an argument:

ACTION="javascript:ShowFields(myForm)">

Then, add this procedure to open a new window and save a pointer to that window, in the NewWin variable. Notice that the third argument of the open method allows you to create a small, fixed-size window with no status bar or scroll bars. Then use the write method of the document object within the new window to write the HTML that will be displayed:

function ShowFields(frm)
{
var NewWin = window.open(
   "","", 
   "height=100,width=300,
   status=0,resizable=0,scrollbars=0");
NewWin.document.write("<HTML><HEAD><TITLE>'New
Window'</TITLE></HEAD><BODY>");
NewWin.document.write("Name: " + 
   frm.FName.value + "<br>");
NewWin.document.write("Email: " + 
   frm.Email.value + "</BODY></HTML>");
}

Now that you know enough of the browser's object model to open a new window and write some HTML, you can easily create a tool to help you learn the rest of the object model. JavaScript's standard for...loop statement is similar to the one in C. A block of statements is executed in the loop while a counter is increment to a limit:

 
Figure 2 Create a New Window. You can easily write JavaScript procedures that will create a new browser window and, using the write method of the document object, you can add HTML code to display information from the main window.

 

for (var i = 0; i < 5; i++) {
   n += I
   myfunc(n)
}

But there is also a for...in statement similar to the for...each statement in Visual Basic. This statement iterates a specified variable over all the properties of an object. For each distinct property, JavaScript executes the specified statements. You can use this statement to iterate all the properties of an object. So why not create a routine that lets you select an object, and create a new window with a table showing all of that object's properties and values?

Add this code to your test form to create another select control with values for the window, navigator, document, and form objects. The onChange event will call the SelObject procedure and pass the select control:

<SELECT NAME="Sel1" 
   onChange="SelObject(Sel1)" size="1">
<OPTION SELECTED VALUE=0> --Choose 
   Object-- 
<OPTION VALUE="Window">Window
<OPTION VALUE="Navigator">Navigator
<OPTION VALUE="Document">Document
<OPTION VALUE="Form">Form
</SELECT></p>

 
  Figure 3 Object Browser Window. This is an example of the new window created by the JavaScript object browser procedures. It shows the properties of the form object within an HTML table.

Now, write a SelObject procedure that will create a new window and determine which object was selected. Use a switch statement to assign an object variable to match the selection. Then, use the write method of the document object in the new window to write the first part of the HTML file (including setting up a two-column table for the properties of the object and their values). Finally, use the for...in statement to loop through all the properties of the object and add a row to the table for each property. (See Listing 1 for the complete procedure):

for (var prop in object) { 
   NewWindow.document.write
("<TR><TD>");
   NewWindow.document.write
(prop);
   NewWindow.document.write
("</TD><TD>");
   NewWindow.document.write(object[prop]);
   NewWindow.document.write("</TD></TR>");
   } 

If you run this code for the form object (see Figure 3) you will see several interesting properties, including the inner HTML property that shows the actual HTML of the form. Now you have your own JavaScript object browser; one that will let you quickly learn the properties of the browser's object. Add some hyperlinks to your test HTML page, then look at the links collection of the document object. You can download the complete HTML page with all of the JavaScript object procedures from the registered area of DevX.


Chris Barlow is president of SunOpTech, a developer of document-management, decision-support, and supply-chain applications including the ObjectBank, ObjectOrder, and ObjectJob Systems. He holds two U. S. Patents related to software for decentralized distributed asynchronous object-oriented and scheduling systems. Chris, who is a frequent speaker at VBITS, Tech·Ed, and DevDays and has been featured in two Microsoft videos, holds degrees from Harvard Business School and Dartmouth College. Reach Chris at Chris@VBExpert.com or through his Web server at http://www.VBExpert.com.