Home > Articles > Open Source > Ajax & JavaScript

  • Print
  • + Share This
This chapter is from the book

Workshop: Creating a Navigation Frame

A common use for frames is to display a navigation frame along the side or top of a page. Using frame objects, you can create a navigation frame that controls the document in another frame.

To begin, you'll need a document to define the frameset. This is the simple part. Listing 11.5 defines a frameset with frames on the left and right.

Listing 11.5 An HTML document to divide the window into two frames

<html>
<head>
<title>Frame Navigation Example</title>
</head>
<frameset COLS="*,*">
<frame NAME="left" SRC="left.html">
<frame NAME="right" SRC="about:blank">
</frameset>
</html>

Next, you will need the document for the left-hand frame, which will act as the navigation frame. Listing 11.6 shows the HTML document for this frame.

Listing 11.6 The HTML document for the navigation frame

<html>
<head>
<title>Navigation Frame</title>
</head>
<body>
<p>
Follow one of these links
to load a page into the right-hand
frame:
</p>
<ul>
<li><a HREF="#"
onClick="parent.right.location='order.html';
     window.location='ordernav.html';">
Order form</a>
<li><a HREF="#"
onClick="parent.right.location='email.html';
     window.location='emailnav.html';">
Email</a>
<li><a HREF="#"
onClick="parent.right.location='sales.html';
     window.location='salesnav.html';">
Sales Dept.</a>
<li><a HREF="#"
onClick="parent.right.location='link.html';">
Other Links</a>
</ul>
</body>
</html>

This listing looks complicated, but it actually uses two simple JavaScript statements to do its job. These statements are repeated for each of the links, with a slight variation. Here's one example:

onClick="parent.right.location='email.html';
     window.location='emailnav.html';">

These statements are an event handler that loads a document into the right-hand frame, and also loads a new document into the navigation frame. Because the current script is itself in a frame, you need to use the parent keyword before the name of the other frame's object.

NOTE

If you're only loading one document when the user clicks on a link, you can use the TARGET attribute of the <a> tag and avoid JavaScript. However, using JavaScript allows you to update two frames at once, as seen in this example.

To test this script, make sure that you've saved Listing 11.6 as left.html, and then load Listing 11.5 into the browser. Try one of the links. (You can download a complete set of HTML documents for this example from this book's Web site, http://www.jsworkshop.com.) Figure 11.6 shows Internet Explorer's display of this example.

Figure 11.6. The frame example as displayed by Internet Explorer.

  • + Share This
  • 🔖 Save To Your Account