10.1 JavaScript and the Browser Object Model


JavaScript programs are associated with a browser window and the document displayed in the window. The window is a browser object and the document is an HTML object. In the browser object model, sometimes called BOM, the window is at the top of the tree, and below it are objects: window, navigator, frames [], document, history, location , and screen . See Figure 10.1.

Figure 10.1. The hierarchy of the browser object model.

graphics/10fig01.gif

If you are writing a JavaScript program that needs to manipulate the window, then you would use the window object and properties and methods associated with it. For example, the status property of the window object is used when you want to display text in the status bar, and the window's alert method allows you to send a message to a dialog box.

The document object model refers to the HTML document and all the elements and attributes associated with it. Since your Web page is so closely linked to HTML (or XML), JavaScript uses the document object model, also called DOM, to access the HTML elements and attributes within a page. The document is the root of this model. Each HTML element is assigned to an object: there are image objects, form objects, link objects, and so on (see Figure 10.2). (See Chapter 11, "The Document Objects," for more on document objects and the document object model.)

Figure 10.2. The hierarchy of the document object model.

graphics/10fig02.gif

By combining the browser and document object models, JavaScript allows you to manipulate all of the elements in a page as objects, from the window down the hierarchy, as shown in Figure 10.3.

Figure 10.3. The browser and document object models combined (only a partial diagram).

graphics/10fig03.gif

10.1.1 Working with the navigator Object

The navigator object contains properties and methods that describe the browser. Netscape Navigator and Internet Explorer support the navigator object, but some browsers do not.

The navigator object can be used for platform-specific checking to determine the version of the browser being used, whether Java is enabled, what plug-ins are available, and so on.

Table 10.1 lists the properties that describe the navigator object.

Table 10.1. Properties of the navigator object.

Property

What It Describes

appCodeName

Code name for the browser

appName

Name of the browser

appVersion

Version of the browser

mimeTypes

An array of MIME types supported by the browser

platform

The operating system where the browser resides

userAgent

HTTP user -agent header sent from the browser to the server

Example 10.1
 <html>     <head><title>Navigator Object</title></head>     <body> 1   <script language="JavaScript">        document.write("<font size=+1><b>\        The properties of the \"navigator\" object are:</b><br>"); 2  for(var property in navigator)  { 3         document.write(  property  + "<br>");        }     </script>     </body>     </html> 

EXPLANATION

  1. The JavaScript program starts here.

  2. The special for loop assigns , in turn , each property of the navigator object to the variable called property.

  3. Each property of the navigator object is displayed in the browser window. See Figures 10.4 and 10.5.

    Figure 10.4. In Netscape Navigator, the browser window displaying the properties of the navigator object. Output from Example 10.1.

    graphics/10fig04.jpg

    Figure 10.5. In Internet Explorer, the browser window displaying the properties of the navigator object. Output from Example 10.1.

    graphics/10fig05.jpg

What Is Your Browser's Name? Version Number?

Browsers support different features, properties, and methods; for example, Internet Explorer may display a page in a slightly different form than Netscape Navigator, one version of Netscape might support a feature not supported by an older version, a version of IE might not support a feature supported by Netscape, and so on. Then if you take into consideration all the other browsers and their unique features, it can be tricky to please all of the browsers all of the time or even some of the browsers all of the time. Browser detection allows you to check for specific browser names , versions, whether cookies are enabled, what types of plug-ins are loaded, and so on. The navigator object contains a number of properties that allow you to detect information about the user's browser so you can customize your Web page in a way that is transparent to the user.

What Is a Browser Sniffer?

A browser sniffer is a program that makes browser detection easy. Many Web sites provide free browser sniffers that determine the types of different browsers. If you want to know more about your browser, go to http://www.perlscriptsjavascripts.com/js/browser_sniffer.html.

Example 10.2
 <html><head>     <title>The Navigator Object</title></head>     <body>     <h2>About The Browser</h2>     <script language="JavaScript"> 1      var BrowserName=  navigator.appName;  2      var BrowserVersion =  navigator.appVersion  ; 3      var BrowserAgent=  navigator.userAgent  ;        var platform=navigator.platform;        document.write("<font size='+1'>"); 4      document.write("<b>The Browser's name  is:</b> " +                       BrowserName + "<br>"); 5      document.write("<b>The Browser version is:</b> " +                       BrowserVersion + "<br>"); 6      document.write("<b>The Browser's \"user agent\" is:</b> " +                       BrowserAgent + "<br>"); 7      document.write("<b>The Browser's platform is:</b> " +  platform  + "<br>");        document.write("</font>");     </script>     </body>     </html> 

EXPLANATION

  1. The value of the navigator object's appName property is assigned to variable BrowserName . The value is the name of the browser.

  2. The value of the navigator object's appVersion property is assigned to variable BrowserVersion . The value is the current version of the browser.

  3. The value of the navigator object's userAgent property is assigned to variable BrowserAgent . The value is sent from the browser to the server in the HTTP header as the user agent.

  4. The common name of the browser, Netscape or Microsoft Internet Explorer , is displayed.

  5. The version number of the browser is displayed.

  6. User-agent strings, as shown in this navigator property, are one of many environmental variables used to identify a program to HTTP or mail and news servers, for usage tracking and other purposes ( HTTP_USER_AGENT ). User agents can be browsers, spiders, robots, crawlers ,and the like. For a database of user agents , see http://www.icehousedesigns.com/useragents/. For a complete descripton of each part of the user-agent string see http://www.mozilla.org/build/user-agent-strings.html.

  7. The operating system is in the navigator's platform property. The Windows operating system is the platform on which this browser is currently running. See Figures 10.6 and 10.7 for the complete output.

    Figure 10.6. The output from Example 10.2 shown in Netscape Navigator.

    graphics/10fig06.jpg

    Figure 10.7. The output from Example 10.2 shown in Internet Explorer.

    graphics/10fig07.jpg

Detecting Plug-Ins

Plug-ins are special software programs that can be downloaded to add the ability to listen to audio, watch videos and movie clips, display animation, and create special image viewing files. Some examples of plug-ins are Macromedia Shockwave or Flash player, Adobe Acrobat Reader, and RealNetworks RealPlayer. Plug-ins can be platform dependent and their MIME types may vary as well. If you are using Netscape, go to the Help menu and select About Plug-ins to get more information about the plug-ins supported on your client.

The plugins[] array of the navigator object (starting with Navigator 3) contains a complete list of installed plug-ins and can be numerically indexed to see all plug-ins installed for this browser, specifically Netscape. Each element of the plugins[] array represents a plugin object. The properties of the plugin object are shown in Table 10.2. When you use the HTML <embed> tag in a document, you are creating a plugin object. Each instance of the <embed> tag creates another object. See "The embeds Object" on page 346 in Chapter 11, and the discussion on page 210 of the <object> tag for embedding objects.

Table 10.2. Properties of the plugin object.

Property

What It Describes

description

A description of the plug-in

filename

The disk filename of the plug-in

length

The number of elements in the plugins[] array's mimeType object; e.g., navigator.plugins["Shockwave"].length

name

The name of the plug-in

Example 10.3
 <html><head><title>Plugin Detection</title></head>     <script language="JavaScript"> 1  function pluginDetector(type) {  2  if (navigator.plugins[type]){  return true;           }           else{              return false;           }        }     <body bgcolor="magenta">     <font face="verdana">     <script language="JavaScript"> 3      var plugin = prompt("What plugin do you want to check                            for?",""); 4  if (pluginDetector(plugin)){  //  Does the browser  //  support plug-ins?  alert("You have the plugin "+ plugin);        }        else{           alert("Don't have the plugin");        }     </script>    </body></html> 

EXPLANATION

  1. A JavaScript function, called pluginDetector() , is defined. It takes one parameter, the name for a type of plug-in.

  2. If the plug-in is installed, the function will return true; otherwise false.

  3. The user is asked to input the name of a plug-in he would like to check for. See Figure 10.8.

    Figure 10.8. Checking for a Netscape plug-in called Shockwave Flash.

    graphics/10fig08.jpg

  4. If the pluginDectector() function returns true, the alert message will report that the user's browser supports the named plug-in. See Figure 10.9.

    Figure 10.9. The plug-in is installed.

    graphics/10fig09.jpg

Example 10.4
 <html><head><title>Plugin Detection</title>     </head><body bgcolor="lightgreen">     <font face="arial" size="+1">     <h2>Installed Plugins (Netscape)</h2>     <script language="JavaScript"> 1      for ( var i = 0;i <  navigator.plugins.length  ; i++){ 2      document.write ("<br>"+  navigator.plugins[i].name  +"<br>"); 3         if(  navigator.plugins[i].description  ){              document.write ("<font size='-1'>"+ 4  navigator.plugins[i].description  +              "<font size='+1'<br>");           }        }     </script>     </body></html> 

EXPLANATION

  1. The plugins[] array consists of a list of plug-ins that have been installed in this browser. The for loop is used to go through the array, one by one, listing each plug-in. The length property specifies the number of elements in the plugins[] array. If using IE for Windows, then you will need to use the HTML <object> tag and identify a class ID. (See http://msdn.microsoft.com/library/default.asp?url=/workshop/ components /activex/activex_ovw_entry.asp for a tutorial on ActiveX.)

  2. The name property specifies the actual name of the plug-in.

  3. The description property gives more detail about what the plug-in does. If it is not null, the block is entered.

  4. A description of the plug-in is displayed, as shown in Figure 10.10.

    Figure 10.10. Netscape plug-ins.

    graphics/10fig10.jpg

What Is ActiveX?

Athough IE 4 defines the plugins[] array, it is always empty because Internet Explorer for Windows versions 5.5 SP2 and 6.0 no longer support Netscape-style plug-ins. Instead of plug-ins, Microsoft has something called ActiveX controls.

IE for Windows uses ActiveX controls instead of Netscape plug-ins or Java applets. ActiveX controls are used as a means to embed objects or components into a Web page. Online spreadsheets, word processors, patches, and timers are examples of such components. The plug-ins we describe here are ActiveX controls and can be downloaded from vendor sites on the Internet. You can add ActiveX controls to your Web pages by using the standard HTML <object> tag. The <object> tag takes a set of parameters that specify which data the control should use and define its appearance and behavior.

Example 10.5
 <html><head>A Sample of ActiveX Control     <title>ActiveX Example</title></head>     <body> 1   <object id="realaudio1" width=0 height=0 2   classid="clsid:CFCDAA03-8BE4-11CF-B84B-0020AFBBCCFA"> 3   <param name="_ExtentX" value="0">     <param name="_ExtentY" value="0">     <param name="AUTOSTART" value="0">     <param name="NOLABELS" value="0"> 4   </object>     </body> 

EXPLANATION

  1. The ActiveX control is found in the <body> of the HTML document. It starts with the <object> tag to represent the ActiveX control. The ID contains information about the type of control; in this example, the ID is RealAudio1 .

  2. Then classid is assigned clsid , which gives the location of the control: in CFCDAA03-8BE4-11CF-B84B-0020AFBBCCFA.

  3. The parameters are used to control the appearance and functionality of the control.

  4. The ActiveX control is closed with the </object> tag. (See http://msdn.microsoft.com/library/default.asp?url=/workshop/components/activex/activex_ovw_entry.asp for a tutorial on ActiveX.)

What Are MIME Types?

MIME stands for Multi-purpose Internet mail extensions. [1] It is a standard format for sending mail messages across the Internet. Now it is used to exchange all kinds of file types across the Internet, such as audio, video, and image files. All browsers have a list of MIME types. JavaScript 1.1 implemented the mimeType object (see Table 10.3). These objects are predefined JavaScript objects that allow you to access the mimeTypes[] array, a property of both the navigator object and the plugin object. (Note: The mimeTypes[] array will not produce output in IE.)

[1] Available with NN3+ and IE5+ on the Mac, but not on Windows IE.

audio/x-pn-realaudio-plugin is an example of a MIME type for RealPlayer G2 LiveConnect-Enabled Plug-In.

Table 10.3. Properties of the mimeType object.

Property

What It Describes

description

A description of the MIME type

enabledPlugin

A reference to the plugin object for this MIME type

suffixes

A string of filename extensions allowed for this MIME type; e.g., jpeg, jpg, jpe, jfif, pjpeg, pjp object; e.g., navigator.plugins["Shockwave"].length

type

The name of the MIME type; e.g., image/jpeg

Example 10.6
 <html>     <head><title>Mime Detection</title>     </head><body bgcolor="lightgreen">     <font face="arial">     <h2><u>Mime Types (Netscape)</u></h2>     <b>     <script language="JavaScript">         for ( var i=0;i <  navigator.mimeTypes.length  ; i++){ 1          if(  navigator.mimeTypes[i].enabledPlugin != null  ){               document.write ("<br></em><font size='+2'>"+ 2  navigator.mimeTypes[i].type  +"<br>");               document.write("<font size='+1'>               Enabled Plugin Name: <em>"+ 3  navigator.mimeTypes[i].enabledPlugin.name  +"<br>");               document.write("</em>Description: "+ "<em>"+ 4  navigator.mimeTypes[i].description  +               "<br></em>Suffixes: "+ "<em>"+ 5  navigator.mimeTypes[i].suffixes  +"<br>");               }         }     </script>     </body></html> 

EXPLANATION

  1. If the MIME type for a plug-in is not null, the information about it is printed.

  2. This is the MIME type of the plug-in, such as application/x-mplayer2 or application/x-shockwave-flash .

  3. This is the enabled plug-in referred to by this MIME type.

  4. The MIME type is described; such as Acrobat(*.pdf) or Network Interface Plugin (*.nip).

  5. The suffixes are the filename extensions that this MIME type supports, such as .rpm, .wav, .pdf, and so on. Partial output is shown in Figure 10.11.

    Figure 10.11. MIME types. Output from Example 10.6 (partial list).

    graphics/10fig11.jpg

10.1.2 Working with the window Object

The window object is where all the action happens in a browser. It's at the top of the JavaScript hierarchy, and is automatically defined for each window that you open, as represented in Figure 10.12. When you start up your browser, you may stay in the current window until you exit the browser, or you may have any number of windows open at the same time. Within each window you browse the Internet, read e-mail, search for cheap airline tickets, and buy a new book. Each new page you bring up is a document within the current window. The window is often partitioned into independent display areas, called frames, which are windows within windows. (Frames are discussed in "Working with Frames" on page 231.)

Figure 10.12. Any number of windows, each with assorted objects.

graphics/10fig12.jpg

The window object comes with a number of properties and methods. Since it is the basis of all objects, the name of the window object can be excluded when applying methods to it; for example, it is not necessary to specify window.alert("Watch out!") or window.document.write("OK") . You simply use alert("Watch out!") or document.write("OK") .

When a user clicks on a button or rolls the mouse over a link, an event occurs which often effects the behavior of a window. Such user-intiated events are discussed in Chapter 12, " Handling Events."

The window Object's Properties and Methods

The window object has a number of properties, which are also objects in their own right. Table 10.4 lists those properties and how they describe the attributes of the window.

Table 10.4. Properties of the window object.

Property

What It Describes

closed

True if the window is closed

defaultStatus

The default status message displayed in the status bar at the bottom of the window

document

The document object that is currently displayed in the window

frames

An array of frame objects within the window

history

The history object containing the URLs last loaded into the window

length

The number of frames within the window

location

The URL of the current window

name

The name of the window

offscreenBuffering

Used to draw new window content and then copy it over existing content when complete; Controls screen updates

opener

The window that opened the current window

parent

Indicates a window that contains another window (used with frames)

screen

Displays information about the screen, e.g., height, width (in pixels) [a]

self

Refers to the current window

status

Specifies a temporary message in the status bar, resulting user interaction

top

The topmost window containing a particular window (used with frames)

window

Identifies the current window being referenced

[a] A new property of the window object, version 4 and above of Netscape and Internet Explorer.

The window object also has a number of methods that define its behavior, such as how to open, close, scroll, and clear a window. They are listed in Table 10.5.

Table 10.5. Methods of the window object.

Method

What It Does

alert(text)

Creates a triangular dialog box with a message in it

blur()

Removes focus from the window

clearInterval(interval)

Clears a previously set interval timer

clearTimeOut(timer)

Clears a previously set timeout

close()

Closes a window

confirm()

Creates a dialog box for user confirmation

focus()

Gives the focus to a window

open(url, name, [options])

Opens a new window and returns a new window object

prompt(text, defaultInput)

Creates a dialog prompt box to ask for user input

scroll(x, y)

Scrolls to a pixel position in a window

setInterval(expression, milliseconds )

After a specified interval, evaluates an expression (see Examples 10.10 and 10.12)

setInterval(function, milliseconds, [arguments])

After a specified interval, evaluates a function (see Examples 10.10 and 10.12)

setTimeout(expression, milliseconds)

After a timeout period has elapsed, evaluates an expression (see Examples 10.10, 10.11, and 10.13)

setTimeout(function, milliseconds, [arguments])

After a timeout period has elapsed, evaluates a function (see Examples 10.10, 10.11, and 10.13)

Opening and Closing Windows

You can open a new browser window by going to the File menu and selecting New Window (Netscape and IE), or you can open a new window from a JavaScript program with the window's open method.

FORMAT

 
 var window_object =  window.open("url", windowname, [options]); 

Example:

 
 var winObj= window.open("http://localhost/windows/winter.jpg",    "winter","width=1150,height=350,resizable=yes,scrollbars=yes,    location=yes"); 
Example 10.7
 <html>     <head><title>Opening a New Window</title>     <script language="JavaScript"> 1  function newWindow(){  2  var winObj=open("winter.jpg", "winter");   }  </script>     </head>     <body bgColor="lightblue">        <h2>Winter Scene from the Old Country</h2>        <h3>Click here to see through my winter window<br> 3  <a href="javascript:newWindow()">Winter Scene</a></h3>  </body>     </html> 

EXPLANATION

  1. The JavaScript function newWindow is defined.

  2. The open method is called and returns a window object that is assigned to the variable, winObj . The first agument to the open method is the URL of the new window; in this case the document is an image file called winter.jpg located in the current directory. The name to be associated with this window is winter .

  3. When the user clicks on the line Winter Scene , the JavaScript user-defined function, newWindow , is called (see Figure 10.13). This function is responsible for opening the new window. Instead of a URL, the HTML < a href > tag is assigned name of a JavaScript function. The javascript: label allows the function to be called when the user clicks on the link. Without the javascript: label, the browser will try to find a URL address called newWindow(), and fail.

    Figure 10.13. A new window showing a winter scene is opened.

    graphics/10fig13.jpg

The window object's open() method has a number of options that allow you to further customize the new window. They are listed in Table 10.6.

Table 10.6. The open() method and its options.

Option

Values

Gives the Window

directories()

yes/no or 1/0

Directory buttons

height

integer value

Height in pixels

location()

yes/no or 1/0

A location box

menubar()

yes/no or 1/0

A menu bar

resizable

yes/no or 1/0

The ability to be resized

scrollbars

yes/no or 1/0

Scrollbars along the side

status()

yes/no or 1/0

A status bar

toolbar()

yes/no or 1/0

A toolbar

width

integer value

Width in pixels

Example 10.8
 <html>     <head><title>Opening a New Window with Parameters        and Closing It</title>     <script language="JavaScript"> 1       function newWindow(){ 2  winObj=window.open("http://localhost/windows/winter.jpg",   "winter","width=1150,height=350,resizable=yes,   scrollbars=yes,location=yes");  3  winObj.focus();  4          //winObj.blur();         } 5       function closeWindow(){ 6  winObj.close();  }     </script>     </head>     <body bgColor="lightblue">     <h2>Winter Scene from the Old Country</h2>     <h3>Click the link to see my winter window<br> 7  <a href="javascript:newWindow()">Winter Scene</a>  <p>When you are ready to close the window, click here<br> 8  <a href="javascript:closeWindow()">Close the window</a></h3>  </body></html> 

EXPLANATION

  1. The function newWindow() is defined.

  2. The open() method is passed the URL of the jpeg image file that will be displayed in the new window called winter . The width and height of the new window are 1150 and 350 pixels, respectively. The window is resizeable and has scrollbars. A location box appears in the top of the new window. The name of the window object created by the open method is winObj . It is important that you use no spaces or linebreaks between the commas in the list of parameters.

  3. The focus() method brings the new window into focus: it appears in front of the parent window or any other windows.

  4. The blur() method (commented out) would push the window behind any other windows that are open.

  5. The user-defined function, closeWindow() , is defined.

  6. The reference to the window object, winObj , will call the close() method to close the new window that was opened.

  7. The newWindow function is called when the user clicks on the link Winter Scene . The label, javascript: , prevents the link from trying to activate a URL, and instead goes to the JavaScript program and calls the function closeWindow() . See Figure 10.14.

    Figure 10.14. Opening a new resizeable window with a scrollbar and size dimensions in pixels. Output from Example 10.8.

    graphics/10fig14.jpg

  8. When the user clicks on this link, the new window will be closed. The original or parent window will remain in the browser. If the name of the new window object is not provided, the close() method will try to close the parent window.

Moving and Resizing a Window

JavaScript provides several methods with which to resize and move a window object. The window can be moved or resized absolutely , or relative to its current position or size. The numbers , given as arguments, are the pixel coordinates. They are listed in Table 10.7.

Table 10.7. Move and resize methods.

Method

Example

What It Doe

moveBy

moveBy(20,20)

Moves the window relatively by 20 pixels

moveTo

moveTo(0,0)

Moves to the top, left-hand corner of the screen

resizeBy

resizeBy(15,10)

Resizes the window relatively by 15 x 10 pixels

resizeTo

resizeTo(450,350)

Resizes the window absolutely to 450 x 350 pixels

Example 10.9
 <html>     <head><title>Move a New Window</title>     <script language="JavaScript">         function directions(){ 1          winObj=window.open("myplace.html","myplace",               "width=200,height=300,  resizable=no");  2  winObj.moveTo(0, 0);  //  Move window to top left-hand corner  3  winObj.focus();  4  parent.window.moveTo(215, 0);  //  Move the parent window  5  parent.window.resizeTo(400,400);  //  Resize browser window  }  function closeWindow(){   winObj.close();  }     </script>     </head>     <body bgColor="lightblue">     <h2>We've moved!</h2>     For directions to our new place,     <br>     click the button 6   <form >        <input type="button"           value="Simple Directions" 7         onClick="directions();">     <p>When you are ready to close the window, click here<br>     <a href="javascript:closeWindow()">Close the window</a></h3>     </body>     </html> 

EXPLANATION

  1. A new window object is created. If the resizeable option is turned off, the user will not be able to maximize the window. A maximized window cannot be moved with the moveTo() method.

  2. The moveTo() method determines the position where the window will be moved. The arguments 0,0 represent the x,y coordinates (column,row) in pixels.

  3. The new window will be put into focus, meaning it will be at the top of the window hierarchy, in front of all the other windows.

  4. The parent window is the original window we started in. It is moved to coordinates 215 x 0 pixels.

  5. The parent (original) window is resized to 400 x 400 pixels.

  6. This is the start of a simple HTML form. It creates a simple input device called a button on the screen.

  7. This is the onClick event. When the user presses the button, the event is triggered and the handler, a function called directions() , will be called. The new window is moved to the top left-hand corner and put into focus. See Figure 10.15.

    Figure 10.15. After moving, focusing, and resizing both the new window and the parent window. Output from Example 10.9.

    graphics/10fig15.jpg

Creating Timed Events

The window object provides a method that acts like an alarm clock so that you can time when you want certain things to happen in your program. The setTimeout() method evaluates an expression after a specified amount of time. The setTimeout() method has two arguments: a quoted expression, and the time in milliseconds to delay execution of the expression. (A minute contains 60,000 milliseconds, so 30 seconds would be 30,000 milliseconds.) Since JavaScript sees time in terms of milliseconds, Table 10.8 gives you a little conversion table to help determine the time in milliseconds.

Table 10.8. Basic units of time.

Unit of Time

Milliseconds

1 second

1000

 

1 minute

second * 60

(1000 * 60)

1 hour

minute * 60

(1000 * 60 * 60)

1 day

hour * 24

(1000 * 60 * 60 * 24)

1 week

day * 7

(1000 * 60 * 60 * 24 * 7)

If a function contains a setTimeout() method that in short intervals keeps invoking the function, the result can give the effect of continuous motion such a scrolling panorama or message, or even animation. [2] Often, timers are used to scroll messages in the title or status bars repeatedly. You must decide what is tasteful on your Web page and what is annoying, but that aside, we use setTimeout() and clearTimeout() methods for scheduling something to happen in the future.

[2] For an example of a timer to create animation, see Chapter 15, "Dynamic HTML: Style Sheets, the DOM, and JavaScript."

As of JavaScript 1.2, the setInterval() and clearInterval() methods were introduced for automatically rescheduling the execution of code at defined intervals.

The setTimeout() method is a window method. It takes two parameters:

  1. The statements to execute, enclosed in quotes

  2. The time in milliseconds to wait before the statements are executed

FORMAT

 
 var timeout = setTimeout("expression", delaytime); var timeout= setInterval("expression", intervaltime); 

Example:

 
 var timeout = setTimeout("timer()", 15000);  //  In 15 seconds call the  //  function "timer()"  var timerId = setInterval("scroller()", 500);  //  In .05 seconds call  //  "scroller()"  

To clear the timed event use the clearTimeout() or clearInterval() methods:

 
 clearTimeout(timeout); clearInterval(timerID); 
Example 10.10
 <head><title>The setTimeout method</title>     <script language="JavaScript"> 1  function changeStatusBar(){  2  window.status = "See me now before I disappear!";  3  timeout =setTimeout("window.status=''", 6000);  // alert(timeout);  This value differs in Netscape and IE  }     </script>     <body>     <center>     <font face=arial size=3 color=blue>     The timeout is set for 6 seconds.     <br> 4   <img src="alarm.jpg" border=2>     <p>     Watch the status bar     <br> 5   <form>        <input type="button"        value="click here" 6  onClick="changeStatusBar();"  >     </form>     </center>     </body>     </html> 

EXPLANATION

  1. A JavaScript function, called changeStatusBar() , is defined. Its purpose is to print a message in the status bar of the window for six seconds.

  2. A string value is assigned to the status property of the window. The string " See me now before I disappear! " will appear in the status bar at the bottom of the window.

  3. The setTimeout() method is a window method. After six seconds, the status bar will be set to an empty string.

  4. This is an image of a clock that displays on the screen, just for decoration.

  5. An HTML form starts here. The user will see a button, with the text " click here ," on the button.

  6. When he presses the button, the onClick event is triggered, causing the event handler, changeStatusBar() , to be invoked. See Figure 10.16.

    Figure 10.16. Click the button and watch the status bar. Output from Example 10.10.

    graphics/10fig16.jpg

Example 10.11
 <html>     <!--  This script is a modification of a free script found at           the JavaScript source.           Author: Asif Nasir (Asifnasir@yahoo.com)       -->     <head>     <script language="JavaScript"> 1       var today = new Date(); 2       var future = new Date("December 25, 2003"); 3       var diff = future.getTime() - today.getTime();                            //  Number of milliseconds  4       var days =Math.floor(diff / (1000 * 60 * 60 * 24 ));                            //  Convert to days  5  var str=   "Only " + days + "  shopping days left until Christmas!";  6  function scroller()  { 7          str = str.substring(1, str.length) + str.substring(0,1); 8  document.title=str;  9  window.status=str;  10  setTimeout("scroller()", 300);  //  Set the timer  }     </script>     </head>     <body onLoad = "scroller()">     <b>     <font color=green size=4>     Get Dizzy. Watch the title bar and the status bar!!     <br> 11  <image src="christmasscene.bmp">  </body>     </html> 

EXPLANATION

  1. The Date() constructor creates an instance of a new Date object, called today .

  2. Another Date object is created with the date " December 25, 2003 " assigned to the variable, called future . It would probably be a good idea to make the year a variable, so that we are not always looking at 2003. Try the getFullYear() method to get the current year in four digits.

  3. The difference in millieseconds between the future time and the current time is assigned to the variable called diff .

  4. The milliseconds of time are converted into days, and the result is rounded down by the Math object's floor() method.

  5. The string variable, " Only (number of days goes here) shopping days left until Christmas! ", is assigned to str .

  6. A function called scroller() is defined.

  7. This looks kind of tricky, but here's what's happening. The substr() method extracts everything between the first character and the rest of the string substr ( 1, str.length ), resulting in " nly 19 shopping days left until Christmas! ". Next , another subtsr(0,1) method extracts the first character from the string, the " O ". The " O " is added onto the end of the new string, resulting in "n ly 19 shopping days left until Christmas!O " and after .03 seconds the scroll() function will be called again. Then the string will become " ly 19 shopping days left until Christmas!On ", and then " 19 shopping days left until Christmas!Onl " and so on. Since the substr() method is being called so rapidly , the effect is a scrolling banner.

  8. The new string, str , created by the two substr() methods will appear in the document's title bar. Every time the function is called (i.e., every .03 seconds), the new string will appear, giving a scrolling effect.

  9. The new string will also appear in the status bar of the window.

  10. The timer is set here. The first argument is the name of the function that will be called, and the second argument is how often it will be called, in this case, once every 300 milliseconds or .03 seconds (300/1000). The display is shown in Figure 10.17.

    Figure 10.17. The string " Only 19 shopping days left until Christmas! " scrolls continuously in the title bar and in the status bar. How annoying!

    graphics/10fig17.jpg

Example 10.12
 <html><head><title><Timeout></title>     <script language="JavaScript"> 1       var today = new Date(); 2       var future = new Date("December 25, 2003"); 3       var diff = future.getTime() - today.getTime();                             //  Number of milliseconds  var days =Math.floor(diff / (1000 * 60 * 60 * 24 ));                             //  Convert to days  var str=            "Only " + days + "  shopping days left until Christmas! "; 4  function startup(){  5  setInterval("scroller()",500);   }  6       function scroller(){            str = str.substring(1, str.length) + str.substring(0,1);            document.title=str;            window.status=str;         }     </script>     </head> 7   <  body onLoad = "startup()" bgColor=red  >     <b><font color=green size=4>     Get Dizzy. Watch the title bar and the status bar!!     <br>     <image src="christmasscene.bmp">     </body>     </html> 

EXPLANATION

  1. The Date() constructor creates an instance of a new Date object, called today .

  2. Another Date object is created with the date " December 25, 2003 " assigned to the variable, called future . It would probably be a good idea to make the year a variable, so that we are not always looking at 2003. Try the getFullYear() method to get the current year in four digits.

  3. The difference in milliseconds between the future time and the current time is assigned to the variable called diff . The milliseconds of time are converted into days, and the result is rounded down by the Math object's floor() method.

  4. A function called startup() is defined. It contains the timer method, setInterval() .

  5. The setInterval() method is executed and calls scroller() at intervals of 500 milliseconds, and will continue to do so until the window is exited or the clearInterval() method is called. In Example 10.11 we used setTimeout() instead of setInterval() .

  6. The scroller() function is being called every .05 seconds to send a string to the title bar and status bar of the window. It is explained in detail in Example 10.11. See Figure 10.17 for output.

  7. When the document has finished loading, the onLoad event is triggered. It will call the startup() function and change the background color to red.

Scrolling

Scrolling allows you to move to a particular place in text or an image. If you open up another window, you may want to scroll to a particular place in the window based on the user's selection from a menu in the main window, or you may want to use scrolling to produce an animated effect. For example, if you have a large image that can't be seen in the new window, you can set up scrolling so that you start at the left-hand side of the image and slowly move to the right-hand side and back again, giving a panoramic effect. Scrolling may have different behavior on different browsers. [3]

[3] Example 10.13 works fine on the Netscape browser, but does not work on Internet Explorer because the image is scaled to fit the window no matter what size it is. For this example to work in IE, go to Tools Internet Options Advanced Multimedia, then uncheck the "Enable Automatic Image Resizing" option.

The scrollTo() method takes two arguments, the horizontal and vertical coordinates in pixels to represent the window position, where 0,0 would scroll to the left-hand top corner of the window, and position 0,350 would scroll down 350 pixels from the starting position, and 350,0 would scroll to the right 350 pixels from the starting position, and so on.

FORMAT

 
 window_object.scrollTo(horizontal_pixel_position,vertical_pixel_position); 

Example:

 
 parent.window.scrollTo(0,350); 
Example 10.13
 <html>     <head><title>Scrolling through Autumn</title>     <script language="JavaScript"> 1       winObj=window.open("fallscene.gif","mysscene",        "width=350,height=292,resizable=no");  //  Create the new window  //  with an image.  2  winObj.moveTo(0, 0);  3  winObj.focus();  4       var pixelpos=0; 5  var ImgWidth=1096;  6       var pixelstep = 2; 7       var timeout; 8  function startScroll(){  9         if (pixelpos <= (ImgWidth - 350)){                     //  Check that scrolling is still within the  //  boundaries of the window.  10           pixelpos += pixelstep; 11           winObj.scrollTo(pixelpos,0);   //  Go to that position in  //  the new window  12  timeout=setTimeout("startScroll()",20);  }        } 13  function scrollAgain(){  pixelpos = 0;  //  Reset the horizontal pixel position to 0  14  startScroll();  //  Start scrolling again  }  function stopHere(){  15  clearTimeout(timeout);  //  Stop the clock to stop scrolling  }        function closeWindow(){ 16  winObj.close();  }     </script>     </head>     <body bgColor="lightgreen">     <font face="arial" size=4 >     <b><br><center>     A Window into an Autumn Day     <form> 17     <input type="button"           value="Start scrolling"  onClick="startScroll();">  <input type="button"           value="Stop scrolling"  onClick="stopHere();">  <input type="button"           value="Start over"  onClick="scrollAgain();">  </form>     <font size=-1>     <p>When you are ready to close the window, click here<br> 18  <a href="javascript:closeWindow()">Close the window</a></h3>  </body>     </html> 

EXPLANATION

  1. A new window object is created. It will contain a .gif image of a fall scene.

  2. The new window object is moved up to the top left-hand corner of the browser (coodinates 0,0).

  3. The focus() method puts the window on top of all other opened windows.

  4. The initial pixel position that will be used for scrolling is set to 0.

  5. The variable ImgWidth is assigned 1096 , which will be used to represent the size of the image in pixels.

  6. Each time the image moves to the right, it will be moved 2 pixels in intervals of .02 seconds.

  7. A variable called timeout is declared. It will hold the value returned from the setTimeout() method.

  8. A function called startScroll() is defined. It will start the image scrolling from the left of the screen to the right. If the scrolling is stopped before it reaches the end, this function will start scrolling where it left off.

  9. If the value of the variable pixelpos is less than the width of the window, keep going.

  10. Add one to the pixel postition.

  11. Scroll horizontally to the new pixel position in the window. Moves over one pixel to the right.

  12. Set the timeout to 20 milliseconds: scroll the image to the right, 50 times per minute.

  13. A function called scrollAgain() is defined.

  14. Scrolling starts again.

  15. Stops the scrolling by clearing or turning off the timer.

  16. This function closes the window.

  17. Three buttons will be displayed. A function to start, stop, or restart the scrolling will be called depending on which button the user presses.

  18. If the user clicks on this link, the window with the image will be closed. See Figures 10.18 and 10.19.

    Figure 10.18. The new window on the left has a scene that will scroll by slowly; it can be stopped, and then restarted.

    graphics/10fig18.jpg

    Figure 10.19. This is the scene that will be scrolling by in the small window above.

    graphics/10fig19.jpg

10.1.3 Working with Frames

When you look out the window from the room where you might be at the moment, it may be one big pane of glass like a picture window, or the window may be divided up into panes of squares or rectangles, as shown in Figure 10.20.

Figure 10.20. Windows can have many frames.

graphics/10fig20.jpg

The browser is a virtual window that can be divided up into frames ”independent windows, like panes, within the main window, where each frame is used to display different information. Frames were invented by Netscape. [4] Web designers have debated the merit of using frames because they are often misused and have some distinct disadvantages discussed later in this chapter.

[4] Netscape versions below 2.0 do not support frames.

The file that defines the layout of the frames is called the parent window, and each of the frames it describes is called a child (see Figure 10.21). Although you can't see the parent window, it will show up in the browser's source for the page.

Figure 10.21. The parent window is divided into child frames.

graphics/10fig21.gif

To build frames in a Web page, you use the HTML <frameset> tags instead of the <body> tags (see Table 10.9). At least three files are needed to create frames. The first file defines the layout of the frames (or subwindows) by defining the size and position of the frames. The rows and cols attributes of each frameset specify how much room the frame will need within the window. These values use exact pixels as a default, although you can also use percentages to represent a section of the window, or an asterisk * to allocate leftover space. (These size values will be shown in Examples 10.14 and 10.15.)

Creating HTML Frames

In Example 10.14 the window is divided into two frames: a left-hand frame that takes up 25 percent (in columns) of the window and a right-hand frame that takes up 75 percent (in columns ) of the rest of the window. Since files are required to accomplish this, the main file defines the frameset, the second file contains the HTML code for the left-hand frame, and the third file contains the HTML code for the right-hand frame.

Table 10.9. HTML frame tags.

Tag

Attribute

What It Does

<FRAMESET>

 

Defines a collection of frames or other framesets

 

BORDER

Sets frame border thickness (in pixels) between all the frames

 

FRAMEBORDER

Draws 3D separators between frames in a frameset. A value of 1 or yes turns frame borders on; a value of or no turns them off

 

ROWS

Defines the number and size of rows in a frameset

 

COLS

Defines the number and size of columns in a frameset

<FRAME>

 

Defines attributes of specific frames

 

NAME

Used by JavaScript to reference the frame by name

 

SRC

The URL or location of the frame

Example 10.14
 <html>     <head><title>Frame Me!</title></head>     <!--  Creating the framesets for two files  -->     <!--  This file is named: framesets.html  --> 1  <frameset cols="25%,75%">  2  <frame src="leftframe.html" >  3  <frame src="rightframe.html" >  4  </frameset>  </html> ----------------------------------------------------------------------     <html>     <head><title>Left Frame</title></head>     <!-  -   This file is named: leftframe.html  --> 5   <body bgColor="yellow">     <h2> 6   Just to show you that this is the left frame     </h2>     </body>     </html> ----------------------------------------------------------------------     <html>     <head><title>Right Frame</title></head> 7   <!-  -   This file is named: rightframe.html  --> 8   <body bgColor="lightgreen">     <h2>     Just to show you that this is the right frame     </h2>     </body>     </html> 

EXPLANATION

  1. This is the parent file that defines how the window will be divided into frames. The first frame will take up 25 percent of the page in columns and the second frame will take up the rest of the page, 75 percent.

    graphics/10inf02.gif

  2. The frame src attribute is assigned the URL of the first HTML file, leftframe.html , that will be displayed in the window.

  3. The frame src attribute is assigned the URL of the second HTML, rightframe.html, that will be displayed in the window.

  4. The frameset definition ends with the </frameset> tag.

  5. The background color of the left-hand frame will be yellow.

  6. This text appears in the left frame.

  7. This section represents the right-hand frame.

  8. The background color of this frame is light green. See Figure 10.22.

    Figure 10.22. Two vertically positioned frames. Output from Example 10.14.

    graphics/10fig22.jpg

The next example shows a window partitioned into three horizontal frames.

Example 10.15
 <html>     <head><title>Frame Me!</title></head>     <!--  This file simply defines the frames; it points to other   HTML files (not shown) that comprise the HTML   content  --> 1  <frameset rows="130,*,*" frameborder="yes"   border="1" framespacing="0">  2       <frame src="topframe.html" > 3       <frame src="main.html" scrolling="no">         <!--main.html is the middle frame -->         <frame src="bottomframe.html" > 4  </frameset>  </html> 

EXPLANATION

  1. This time the frameset will be divided up into three sections by rows. The first frame will be a horizontal frame consisting of 130 pixels in a row. Based on the amount of space taken up by the first frame, the remaining frames will be allocated whatever space is left in the window. There are three frames that will be placed horizontally on the page.

    graphics/10inf03.gif

  2. This is the URL to the first frame, topframe.html , which will be at the top of the window.

  3. This is the URL to the second frame, main.html , which will be in the middle of the window.

  4. This is the URL to the third frame, bottomframe.html , which will be at the bottom of the window.

Figure 10.23. Three horizontal frames created in Example 10.15.

graphics/10fig23.jpg

The frame Object

HTML frames in JavaScript are represented as an array of frame objects. The frames[] array is a property of the window object and is referenced with the window's parent property. Each element of the array represents a frame in the order in which it appears in the document; thus, window.parent.frames[0] would reference the first frame defined in a frameset (see Figure 10.24). If you name the frame, then you can reference the frame element by its name. If the frame is named leftframe , it can be referenced as window.parent.leftframe.

Figure 10.24. The JavaScript hierarchy.

graphics/10fig24.gif

Since frames are just little windows, they share many of the same properties and methods of the window object. See Table 10.10 for a list of properties and Table 10.11 for a list of methods.

Table 10.10. Properties of the frame object.

Property

What It Describes

document

The document currently loaded in the frame

frames

An array of frames

length

The number of elements in the frames array; i.e., the number of frames

name

The name of the frame assigned to the HTML name attribute

parent

The main window from which the child frames are defined

self

The current frame

top

The window that started the script

window

The current window or frame

Table 10.11. Methods of the frame object.

Method

What It Does

blur()

Removes focus from the frame

clearInterval()

Clears a timed interval

clearTimeout()

Clears a timeout

focus()

Puts focus into the frame

print()

Invokes a print dialog box

setInterval()

Sets a timed interval

setTimeout()

Sets a timeout

unwatch()

Unsets the watchpoint

watch()

Sets a watchpoint on a frame property; if a property changes, calls a function

Creating Menus and Navigation Bars

Since frames can be used to divide a page, it is common to use one of the frames as a menu of items and the other as the main page where a page is loaded depending on the user's selection. If one frame contains a selection of links, then it can serve as a navigation bar. When the user clicks on a link, the page at that URL will be loaded into the main frame.

In Example 10.16 the frames are defined for two frames. Example 10.17 displays the content of the two frame files. The left-hand frame will represent a menu of links. The background color in the right-hand frame will change when the user clicks on a link in the left-hand frame.

Example 10.16
 <html>     <head><title>Frame Me!</title></head>     <!--  Creating the framesets for two frames  -->     <!-  -   This HTML file is named: framedef.html  --> 1  <frameset cols="25%,75%">  2  <frame src="leftmenu.html"  name=lframe>  3  <frame src="rightcolor.html" name=rframe>  4  </frameset>  </html> 

EXPLANATION

  1. The HTML <frameset> tag replaces the <body> tag when working with frames. The size is determined by the ROWS and COLS attributes of the <frameset> tag. In this example, the first frame will occupy 25 percent of the window, and the second frame will occupy 75 percent of the window (in columns). The default is to set ROWS and COLS in pixels. ( ROWS and COLS are not case sensitive.)

  2. The first frame, named lframe occupies 25 percent of the left-hand side of the window. Its content is in an src file called leftmenu.html .

  3. This frame, called rframe , occupies 75 percent of the right-hand side of the window. Its content is in an src file called rightcolor.html .

  4. The HTML </frameset> tag ends the definition of the frames.

Example 10.17
 <html>     <head><title>Left Frame</title>     <!-  -   This HTML file is named: leftmenu.html  --> 1   <script language="JavaScript"> 2      function setBgColor(color){ 3  parent.frames[1].document.bgColor=color;  //  Or use the frame's name: parent.rframe.document.bgColor  }     </script>     </head>     <body bgColor="white">     <h3>     Pick a color:     <br> 4  <a href="javascript:setBgColor('red')">red</a>  <br>  <a href="javascript:setBgColor('yellow')">yellow</a>  <br>  <a href="javascript:setBgColor('green')">green</a>  <br>  <a href="javascript:setBgColor('blue')">blue</a>  </h3>     </body>     </html>     ------------------------------------------------------------------     <html>     <head><title>Right Frame</title></head>     <body>     <h2>     This is the frame where colors are changing.<br>     In your javascript function, this is frame[1].     </h2>     </body>     </html> 

EXPLANATION

  1. A JavaScript program starts here.

  2. A function called setBgColor() is defined. It takes one parameter, a reference to a color being passed by the user.

  3. Going down the document tree, start with the parent window, to the second frame, frames[1] (remember array subscripts start at 0), to the frame's document, and then the document's property, bgColor. Assign a color .. This assignment will cause the background color in the right-hand frame to change.

  4. When the user clicks on any of the following links, the JavaScript function setBgColor() will be called, with the color sent as an argument to the function. The javascript: pseudo URL prevents the link from going to a real URL. The display is shown in Figure 10.25.

    Figure 10.25. When the user clicks on a link in the left-hand frame, the background color in the right-hand frame changes. Ouput from Example 10.17.

    graphics/10fig25.jpg

Using the top Property to Keep the Main Window out of a Frame

If you create a Web page, it should load into the user's main browser window, not in one of the frames. You can use the location method to force your page to load in the main window by putting the JavaScript code shown in Example 10.18 into the <head> portion of the page. Every window and frame has a top property, a reference to the topmost window object currently loaded in the browser. (See "The location Object" on page 244.)

Example 10.18
 <html><head><title>Forcing the Frame</title> 1   <script language = "JavaScript"> 2      if (  window != top  ) {     //  True if window is not the top  //  window in the hierarchy  3  top.location.href = location.href;  //  Put this window on top  }     </script> 4   <body bgcolor="lightblue">     <h1>     The important page that we're talking about     <h2>     </body>     </html> 

EXPLANATION

  1. The script begins here.

  2. If the current window is not at the top of the window hierarchy in the browser, the statement in the block is evaluated. The top property references the highest object in the window hierarchy.

  3. If the current window isn't at the top of the window hierarchy (if it's not the main window), this assignment forces the page, location.href , into the main window, top.location.href .

  4. This is the body of the fictitious page that will be loaded into the main window of whoever views it.

Collapsing Toolbars and Menu Bars

You don't always necessarily want to look at the toolbar or menu bar. It can be in the way of what you're viewing in the main page. Example 10.19 collapses the frame in order to bring the main frame to the foreground so that it will be viewed in the entire window.

Example 10.19
 <html>     <head>     <title>Untitled Document</title>     <meta http-equiv="Content-Type"        content="text/html; charset=iso-8859-1">     </head>     <frameset cols="117,450" rows="*">  <frame src="toctoolbar.html" name="menu">   <frame src="tocmain.html" name="main">  </frameset>     <noframes><body bgcolor="#FFFFFF">     </body></noframes>     </html> ----------------------------------------------------------------------     (The Startup Main Page)     <html>     <head>     <title>Untitled Document</title>     <meta http-equiv="Content-Type" content="text/html;        charset=iso-8859-1">     </head>     <body bgcolor=yellow>     <h1>This is the main page</h1>     <body bgcolor="#FFFFFF">     </body>     </html> ----------------------------------------------------------------------     (The Menu Bar Page)     <html>     <head>     <title>Menu Bar</title>     <meta http-equiv="Content-Type" content="text/html;        charset=iso-8859-1">     <script language="javascript">        var myUrl; 1      function openSite(  url  ){ 2  parent.main.location = url;  3  myUrl=url;  } 4  function collapse(){  if ( ! myUrl){ 5             parent.location = "tocmain.html";}            else{ 6  parent.location=myUrl;  //  Force this page into the  //  parent location  }        }     </script>     </head>     <body bgcolor="#FFFFFF"> 7   <p><a href="javascript:openSite('tocmain.html')">Home</a><p>     <p><a href="javascript:openSite('http://ellieq.com');">        Page 1</a></p>     <p><a href="javascript:openSite('http://prenticehall.com');">        Page 2</a></p>     <p><a href="javascript:openSite('http://google.com');">        Page 3</a></p> 8   <p><a href="javascript:collapse();">Hide Menu</a><p>     </body>     </html> 

EXPLANATION

  1. A function called openSite is defined. It takes one parameter, the URL of the Web site.

  2. The parent is the main window where the frames are defined. main.location is the frame on the right-hand side of the toolbar. It was named main when the framesets were defined. The main frame is assigned the URL of one of the Web sites after the user clicks on a link in the menu bar.

  3. The global variable url gets the URL of the current Web site shown in the right frame.

  4. The function called collapse() is defined. Its function is to make the right frame fit into the whole window, hiding the menu bar.

  5. If the user hasn't selected any page prior to selecting Hide Menu, the main frame will take up the whole window. The location property of the window object refers to the location of the parent window, the main window from where the frames were created.

  6. The location property of the parent window is assigned the URL of the window currently being viewed in the right-hand frame. This forces the right frame to take up the entire window. The menu bar is no longer displayed.

  7. This list of links makes up the menu bar and is in the left-hand frame.

  8. When the user clicks this link, the collapse() function is called, and the menu disappears causing the right frame to take up the entire window.

Figure 10.26. Two frames, a menu, and the main frame. The user clicked on Page 1.

graphics/10fig26.jpg

Figure 10.27. The user clicked Hide Menu . The larger frame has expanded to fill the entire page.Backpaging will take you back to the menu.

graphics/10fig27.jpg

10.1.4 The location Object

The location object is a property of the window object and is used to access the URL of the document currently loaded in the window. In previous examples, we have seen location as a window property, but because it is really also an object itself, it also has properties used to describe the different parts of a URL. (See Table 10.12.)

If you are writing a page containing frames, the entire page may not be picked up by a search engine, such as Yahoo! or Google. Anyone linking to your page via the search engine will only get part of the page, not the complete frameset. Also, when a page is divided into frames, the visitor cannot bookmark the page if the browser is not in the top frameset. The location object can be used to make sure the topmost window is the one currently loaded in the browser. (See "Using the top Property to Keep the Main Window out of a Frame" on page 240.)

FORMAT

 
 javascript: window.location.href="URL"; javascript: window.location.replace("URL"); 

Example:

 
 javascript: window.location.href="http://www.legos.com/"; javascript: window.location.replace("http://www.legos.com/"); 
Table 10.12. Properties of the location object.

Property

What It Describes in the URL

hash

If it exists, the anchor part

host

The hostname:port

hostname

The hostname

href

The entire URL

pathname

The pathname

port

The port number

protocol

The protocol and colon

search

The query string

Table 10.13. Methods of the location object.

Method

What It Does

reload()

Reloads the current URL

replace()

Replaces the current page with a new one

unwatch()

Removes a watch point on the location property

watch()

Sets a watch point on the location property; i.e., calls a function if the property changes

Two methods of interest are replace() and reload() . The replace() method is used to change the location of the current page; that is, to point to another page. It is similar to the href property, but where href puts the new page at the top of the history list, the replace() method removes the current page from the history list and replaces it with the new page. The reload() method behaves like the browser's Reload button. It causes the window's current document to be reloaded.

Loading a New Page into a Frame with the location Object

In Example 10.20, the location object changes the location of the current page. By selecting a Web site, the user is taken to that site, which is displayed in the bottom frame of a frameset.

Example 10.20
 (The file defining the framesets)     <html><title>Changing Location</title>     <html>     <head><title>Frames</title></head>     <frameset rows="130,*" frameborder="yes" border="8"            framespacing="0">  <frame src="location.html" scrolling="no">   <frame src="emptyframe.html" >  </frameset>     </html> ---------------------------------------------------------------------     (The empty file which will be the bottom frame)     <html>     <head><title>Empty Frame</title>     </head>     <body>     </body>     </html> ---------------------------------------------------------------------     <html><head><title>Changing Location</title>     </head>     <script language="JavaScript"> 1  function loadPage(urlAddress){  2  parent.frames[1].location.href = urlAddress;  }     </script>     </head>     <body bgcolor="F8C473">     <font size="+1" face=arial,helvetica>     Pick your bookstore and we'll take you there! 3  <form>  <input type="button"           value="Amazon" 4  onClick="loadPage('../amazon.com/default.htm');">  <input type="button"           value="Borders"           onClick="loadPage('../borders.com/default.htm');">        <input type="button"           value="Prentice Hall"           onClick="loadPage('../prenhall.com/default.htm');">     </form>     </body> 

EXPLANATION

  1. When the function loadPage() is called, it gets the URL address of the bookstore as its only parameter and assigns the address to the location object.

  2. There are two frames in this document. The first frame contains the buttons with the names of bookstores to pick from ”Amazon, Borders, and Prentice Hall. The second frame is empty until the user makes a selection. This statement assigns the URL of the chosen bookstore to the location object by traversing the JavaScript hierarchy, starting at the parent window, to the bottom frame, frames[1] and to the href property of the location object. By doing this, the browser will find the home page of the bookstore, and display it in the bottom frame.

  3. The HTML form starts here. It is a form that displays three graphical buttons. When the user presses on one of the buttons, a function called loadPage() will be invoked and the bottom frame will display its Web page.

  4. The JavaScript onClick event is triggered when the user clicks on the button. The function called loadPage() will be called with the URL of the bookstore. The display is shown in Figure 10.28.

    Figure 10.28. Two frames: The top frame puts the location of the bookstore in the bottom frame.

    graphics/10fig28.jpg

10.1.5 The history Object

The history object is a property of the window object. It keeps track of the pages (in a stack) that the user has visited. The history object is most commonly used in JavaScript to move back or forward on a page, similar to the back button and forward button supported by your browser. The history object can reference only those pages that have been visited; that is, those pages on its stack. It has a length property and three methods called go(), back() and forward() . [5]

[5] Not predictable on Netscape 6.

FORMAT

Examples:

 
 history.go(-3)    //  Go back three pages  history.go(2)     //  Go forward three pages  back()            //  Same as  history.go(-1) forward()         //  Same as  history.go(1) 
Example 10.21
 <html><head>     <title>The History Object</title>     </head>     <script language="JavaScript">        function loadPage(urlAddress){ 1  parent.frames[1].location.href = urlAddress;  }     </script>     </head>     <body>         <font size="+1" face=arial,helvetica>         <form name="form1">         <input type="button"            value="Amazon"            onClick="loadPage('../amazon.com/default.htm');">         <input type="button"            value="Borders"            onClick="loadPage('../borders.com/default.htm');">         <input type="button"            value="Barnes&Noble"            onClick="loadPage('../barnesandnoble.com/default.htm');">         </form>         <form name="form2"> 2       <input type="button"            value="go back" 3  onClick="javascript: history.go(-1);">  4       <input type="button"            value="go forward" 5  onClick="javascript: history.go(1);">  </form>     </body>     </html> 

EXPLANATION

  1. When the user presses the back or forward buttons, he will be moved back and forth to pages opened in the bottom frame of the page. This line loads the page. The other two files that set up the frames are shown in Example 10.20.

  2. This input button will be used if the user wants to go back to the previous page.

  3. The history.go(-1) method will send you back to the previous page you have visited. If nothing happens, you haven't been anywhere yet.

  4. This input button will be used if the user wants to move to the next page.

  5. If you move forward and nothing happens, it's because you don't have anything on the history stack yet; you haven't gone anywhere. But once you load a new page, then go back, you will be able to move foward. The history.go(1) method will then move you forward one page. Output is shown in Figures 10.29 and 10.30.

    Figure 10.29. The user can go back to the previous page or move forward to the next page in the history stack. Output from Example 10.21.

    graphics/10fig29.jpg

    Figure 10.30. The user presses the "go back" button to go to the previous page he visited. Output from Example 10.21.

    graphics/10fig30.jpg

10.1.6 The screen Object

The screen object is a property of the window object and is automatically created when a user loads a Web page. It gives you access to the various properties of the user's screen such as its height, width, color depth, and so on. These are listed in Table 10.14. This can be helpful when designing pages that will require specific dimensions. For example, if the user's available screen width is less that 650 pixels (640x480), you may want to load a smaller image, whereas if it is over 1000 pixels (1024x768), a larger image can be loaded. There are no event handlers for this object.

Table 10.14. Properties of the screen object.

Property

What It Describes

availHeight

The pixel height of the screen, minus toolbars, etc.

availLeft

The x coordinate of the first pixel, minus toolbars, etc.

availTop

The y coordinate of the first pixel, minus toolbars, etc.

availWidth

The pixel width of the screen, minus toolbars, etc.

colorDepth

The maximum amount of colors that the screen can display

height

The pixel height of the screen

pixelDepth

The number of bits per pixel of the screen

width

The pixel width of the screen

Example 10.22
 <html><head><title>Screen Properties</title>     </head>     <body bgcolor="orange" > <font face=verdana>     <script language="JavaScript">     document.write("<b>The Screen</b><br>");     document.write("<table border=2>");     document.write("<tr><th>Screen Property</th><th>Value</tr>"); 1   document.write("<tr><td>Height</th><th>",  screen.height  ,"                    </td></tr>");     document.write("<tr><td>Available Height</th><th>", 2  screen.availHeight  ,"</td></tr>");     document.write("<tr><td>Width</th><th>",  screen.width  ,"                   </td></tr>");     document.write("<tr><td>Available Width</th><th>", 3  screen.availWidth  ,"</td></tr>");     document.write("<tr><td>Color Depth</th><th>", 4  screen.colorDepth  ,"</td></tr>");     document.write("</table>");     </script>     </body>     </html> 

EXPLANATION

  1. The height property of the screen object contains the height of the screen in pixels.

  2. The available height is the height minus any toolbars or other objects attached to the window.

  3. The width property of the screen object contains the width of the screen in pixels.

  4. The colorDepth refers to the maximum number of colors that the screen can display in bit format. The display is shown in Figure 10.31.

    Figure 10.31. Tables showing properties of the screen object in Internet Explorer (left) and Netscape (right).

    graphics/10fig31.jpg



JavaScript by Example
JavaScript by Example (2nd Edition)
ISBN: 0137054890
EAN: 2147483647
Year: 2003
Pages: 150
Authors: Ellie Quigley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net