Lean CSS
Welcome to CSS
Introduction to CSS
CSS Syntax
Insert style sheet
CSS Background
CSS Text
CSS Font
CSS Border
CSS Margin
CSS Padding
CSS List
CSS Dimensions
CSS Classification
CSS Positioning
CSS classes
CSS elements
CSS2 Media Types
CSS Units
CSS Colors
 

Free Tutorials
HTML
Learn HTML
Learn CSS
Learn XML
Learn WML
Database
Learn Access
Learn Data-VB
Learn Oracle
Learn SQL
Programming
Learn C++
Learn JavaScript
Learn Vbscript
Learn VisualBasic

Chapter 8

Improving a Web Page with JavaScript


CONTENTS

Although JavaScript is useful for forms, it can also be useful for an ordinary Web page. It can add user-friendliness, convenience, and eye-catching gadgets to liven up a page.

In this chapter, you will look at some of the ways JavaScript can improve a Web page. You'll start with a simple Web page, then add interactive features with JavaScript.

The Beginning: A Simple Web Page

Let's begin with an example of a typical Web page. Once again let's use FSC (the Fictional Software Company) as an example. FSC has a simple set of Web pages that introduce the company and include detailed information about each of the products.

Although the FSC pages are functional and include good information about the company and its products, they're not about to win any awards. In this chapter and the next, you'll learn how JavaScript can make the page more friendly and exciting.

The Main Page

The main FSC Web page is shown in Figure 8.1. It includes a logo at the top, three paragraphs of information, and a simple bulleted list of links to the various subpages. This page is defined using the HTML in Listing 8.1.

Figure 8.1 : A simple Web page using only HTML.


Listing 8.1. (FSchOME.asp) The HTML document for the initial FSC Web page.
<HTML> <HEAD><TITLE>Fictional Software Company</TITLE></HEAD> <BODY> <IMG SRC="fsclogo.gif" alt="Fictional Software Company"> <HR> Welcome to our web page! Fictional Software Company specializes in creating innovative, user-friendly software applications with descriptions filled with industry buzzwords. <P>We have a wide range of products (3 of them) to meet the needs of you and your company. Follow the links below for more information. <P> <UL> <LI><A HREF="spread.asp">Fictional Spreadsheet 7.0</A> <LI><A HREF="word.asp">Fictional Word Processor 6.0</A> <LI><A HREF="data.asp">Fictional Database 7.0</A> </UL> <P> Unlike other software companies, our products have absolutely no bugs, and always work perfectly on all computers. Nevertheless, you may run into problems in rare cases, usually your own fault. If this happens, visit our <A HREF="support.asp">Technical Support</A> department for helpful information and tips. You can also view more information <A HREF="company.asp">about our company</A> or order products with our friendly <a href="order.asp">Order Form</A>. <HR> <I>(c)1998 FSC - designed by the FSC staff</I> </BODY> </HTML>

The various links on the page send you to the company's other pages. One describes each of the company's products, another contains information about the company, and another gives technical support information. A link is also provided to the order form, which was created in Chapter 6 "Using Interactive Forms."

Creating a Navigation Bar

More recently, FSC decided to add more detailed information to its pages. The main page remains the same, but each product's page is now a menu of links to subpages with various categories of information.

As it is, the pages can be difficult to navigate. For example, if you want to view the system requirements for the Fictional Word Processor product, you must select the product name from the main page, wait for the page to load, then select the "System Requirements" link.

With JavaScript, you can create a friendly interface to all the pages on the main page-without taking much space. Let's use one selection list to choose the product and another selection list to choose the type of information about the product to view.

Note
In this example, the two selection lists stay the same because each product has the same categories of information available. You will learn a technique for changing the contents of a selection list in Chapter 11, "Real-Life Examples II."

Naming the Pages

In writing a program, the programming isn't always the hardest part. You should define the task the program will perform and the data it will use in advance; this will make the actual task of writing the program simple.

In order to make the navigation bar programming task easier, let's choose simple, meaningful names for each of the subpages. This will make it easy to construct their names based on the value of the selection lists.

Assign a one-letter code to each product: w for the word processor, s for the spreadsheet, and d for the database. Then follow that with an underscore and a word indicating the type of information. Here are the categories of information and their corresponding codes:

  • tech: Technical support for the product
  • sales: Sales and availability information
  • feat: A list of features
  • price: Pricing information for the product
  • tips: Tips for getting the most of the product

For example, s_feat.asp is the features list for the spreadsheet program. Meaningful names like this are a good idea in any HTML task, because they make it easier to maintain the pages. When you're automating with JavaScript, they can make a big difference.

Note
To try this example yourself, you'll need all the individual HTML files. This chapter does not present them, because they're simple HTML; however, the complete set of files is on the CD-ROM included with this guide.

Creating the Data Structures and HTML for the Navigation Bar

Before you write the function to navigate the pages, you need to store the needed data. In this case, you need to store the three codes for the software products and the five codes for types of pages. You could create an array for each list, but that isn't necessary in this case.

Rather than creating an array, you can simply place the information in the HTML page itself, and it will be stored in the properties of the form object by the JavaScript interpreter. You will use the codes as the VALUE attribute of each option.

You will need to define an HTML selection list for each of the lists of information. In addition, the user needs a way to visit the page after selecting it; you will accomplish this with a "go" button next to the drop-down lists.

Listing 8.2 shows the HTML to add to the main page. It's included toward the end of the page, but it's generally self-contained and could be placed anywhere. Chapter 9includes an example of using this same navigation bar within a separate frame.


Listing 8.2. The HTML to define the table of contents.
<FORM name="navform"> <SELECT name="program"> <OPTION VALUE="x" SELECTED>Select a Product <OPTION VALUE="w">Fictional Word Processor <OPTION VALUE="s">Fictional Spreadsheet <OPTION VALUE="d">Fictional Database </SELECT> <SELECT name="category"> <OPTION VALUE="x" SELECTED>Select a Category <OPTION VALUE="tech">Technical Support <OPTION VALUE="sales">Sales and Availability <OPTION VALUE="feat">List of Features <OPTION VALUE="price">Pricing Information <OPTION VALUE="tips">Tips and Techniques </SELECT> <INPUT TYPE="button" NAME="go" VALUE="Go to Page" onClick="Navigate();"> </FORM>

In addition to the categories discussed, I have included an additional option with the value x in each selection list. These options will display an instructional message to the user. Clicking on them will do nothing but will provide the user with a hint about using the selection lists. These are marked as the default selections, so the instructions will be displayed until the user makes a selection.

Tip
When adding features with JavaScript, don't forget to explain their use, especially if you are using a technique used in few other pages. The user shouldn't have to spend any time figuring out how to use your page.

Creating the Function for the Navigation Bar

You defined an onClick event handler for the "go" button, which calls the Navigate() function. Next, you need to create this function. This function will read the current value of both selection lists and construct a filename, then load that file in the browser.

Listing 8.3 shows the Navigate() function. You will look at the features of this function in detail next.


Listing 8.3. The function for navigating based on the selection lists.
function Navigate() { prod = document.navform.program.selectedIndex; cat = document.navform.category.selectedIndex; prodval = document.navform.program.options[prod].value; catval = document.navform.category.options[cat].value; if (prodval == "x" || catval == "x") return; window.location = prodval + "_" + catval + ".asp"; }

To begin, this function sets two variables, prod and cat, to hold the currently selected index for each selection list. Next, prodval and catval are assigned to the corresponding value properties.

The if statement checks for the x value, meaning that the user hasn't yet selected an item, in both lists; if no value has been selected in either list, it returns without doing anything.

Finally, the new document filename is constructed by concatenating the two codes, the underscore (_), and the html suffix. This value is assigned to the window.location property, which causes the new page to be loaded.

Note
Because changing the location property loads the new document, you can't do anything more in the current JavaScript program. In fact, the Navigate() function never returns. However, you could include JavaScript functions on the new page.

Integrating the Navigation Bar with the HTML Page

Your final task is to combine the new navigation form and the Navigate() function with the Web page HTML. Listing 8.4 shows the revised Web page with the new features, and Figure 8.2 shows how the page looks in Netscape.

Figure 8.2 : The revised Web page with interactive table of contents.


Listing 8.4. (NAVBAR.asp) The complete HTML page with table of contents feature.
<HTML> <HEAD> <TITLE>Fictional Software Company</TITLE> <SCRIPT> function Navigate() { prod = document.navform.program.selectedIndex; cat = document.navform.category.selectedIndex; prodval = document.navform.program.options[prod].value; catval = document.navform.category.options[cat].value; if (prodval == "x" || catval == "x") return; window.location = prodval + "_" + catval + ".asp"; } </SCRIPT> </HEAD> <BODY> <IMG SRC="fsclogo.gif" alt="Fictional Software Company"> <HR> Welcome to our web page! Fictional Software Company specializes in creating innovative, user-friendly software applications with descriptions filled with industry buzzwords. <P> We have a wide range of products (3 of them) to meet the needs of you and your company. Follow the links below for more information. <P> <FORM name="navform"> <SELECT name="program"> <OPTION VALUE="x" SELECTED>Select a Product <OPTION VALUE="w">Fictional Word Processor <OPTION VALUE="s">Fictional Spreadsheet <OPTION VALUE="d">Fictional Database </SELECT> <SELECT name="category"> <OPTION VALUE="x" SELECTED>Select a Category <OPTION VALUE="tech">Technical Support <OPTION VALUE="sales">Sales and Availability <OPTION VALUE="feat">List of Features <OPTION VALUE="price">Pricing Information <OPTION VALUE="tips">Tips and Techniques </SELECT> <INPUT TYPE="button" NAME="go" VALUE="Go to Page" onClick="Navigate();"> </FORM> <P> Unlike other software companies, our products have absolutely no bugs, and always work perfectly on all computers. Nevertheless, you may run into problems in rare cases, usually your own fault. If this happens, visit our <A HREF="support.asp">Technical Support</A> department for helpful information and tips. You can also view more information <A HREF="company.asp">about our company</A> or order products with our friendly <a href="order.asp">Order Form</A>. <HR> <I>(c)1998 FSC - designed by the FSC staff</I> </BODY> </HTML>

Note
The one thing missing in this Web page is a way to navigate the pages for non-JavaScript browsers. This could easily be done with normal links; in addition, the form you create could be used to call a CGI script to perform the same function (but a bit slower). You'll learn more about combining JavaScript and CGI in Chapter 17, "Combining JavaScript, CGI, and SSI."

Using the Status Line

As discussed in Chapter 5 "Accessing Window Elements as Objects," you can change the value of the window.status property to display a message on the status line. You can use this feature to add features to a Web page, displaying helpful information about links or about the company.

Creating Friendly Links

Normally, as you move the mouse over each link in a Web page, the status line displays the URL of the link. You can improve on this with JavaScript by displaying a description of the link's destination instead.

You can accomplish this easily using onMouseOver event handlers. When the user moves the mouse over a link, this event will call a function to display the appropriate message on the status line. For example, the following HTML defines a link with a friendly status line:

<A HREF="order.asp" onMouseOver="window.status='Allows you to order products';return true;"> Order form</A>

This simply sets the value of window.status to display the message. In addition, the true value is returned; this is necessary to override the normal action (displaying the URL) for the status line.

Listing 8.5 shows the result of adding onMouseOver functions to each of the links in the original version of the FSC Software page. The page is shown in action in Figure 8.3.

Figure 8.3 : Using event handlers to display link information in the status line.


Listing 8.5. (LINKDESC.asp) The FSC page with the addition of friendly links.
<HTML> <HEAD> <TITLE>Fictional Software Company</TITLE> <SCRIPT> function message(text) { window.status = text; return true; } </SCRIPT> </HEAD> <BODY> <IMG SRC="fsclogo.gif" alt="Fictional Software Company"> <HR> Welcome to our web page! Fictional Software Company specializes in creating innovative, user-friendly software applications with descriptions filled with industry buzzwords. <P> We have a wide range of products (3 of them) to meet the needs of you and your company. Follow the links below for more information. <P> <UL> <LI><A HREF="spread.asp" onMouseOver="window.status='Information about the spreadsheet';return true;"> Fictional Spreadsheet 7.0</A> <LI><A HREF="word.asp" onMouseOver="window.status='Information about the word processor';return true;"> Fictional Word Processor 6.0</A> <LI><A HREF="data.asp" onMouseOver="window.status='Information about the database';return true;"> Fictional Database 7.0</A> </UL> <P> Unlike other software companies, our products have absolutely no bugs, and always work perfectly on all computers. Nevertheless, you may run into problems in rare cases, usually your own fault. If this happens, visit our <A HREF="support.asp" onMouseOver="window.status='Technical Support for our products';return true;"> Technical Support</A> department for helpful information and tips. You can also view more information <A HREF="company.asp" onMouseOver="window.status='Information about FSC Software Co.';return true;"> about our company</A> or order products with our friendly <a href="order.asp" onMouseOver="window.status='Allows you to order products';return true;"> Order Form</A>. <HR> <I>(c)1998 FSC - designed by the FSC staff</I> </BODY> </HTML>

Note
You might be tempted to make a function to avoid using such long statements as event handlers. Unfortunately, because the return true statement must be in the event handler itself, it wouldn't save much typing at all. You can still do it with a command such as return function() in the event handler.

Adding a Scrolling Message

Currently, one of the most common uses of JavaScript is to display a scrolling message on the status line. This might be useful to point out features of the page or to let the user know about a current offer.

Scrolling a message is simple in JavaScript. First, you define a variable with the message to be scrolled, and another with a "spacer" that will be used between copies of the message. A third variable, pos, will be used to store the current position of the string on the status line:

var msg = "Welcome to Fictional Software Company. Watch for a new product coming next month!"; var spacer = "... ..."; pos = 0;

Next, you define a function that will be called periodically to scroll the message. Here is the ScrollMessage() function:

function ScrollMessage() { window.status = msg.substring(pos, msg.length) + spacer + msg.substring(0, pos); pos++; if (pos > msg.length) pos = 0; // set timeout for next update window.setTimeout("ScrollMessage()",200);

}

This function creates the value of the status line by adding three values:

  • The substring of the message, starting at the current position and ending at the end of the string
  • The spacer value
  • The rest of the message, starting at the beginning and ending at the current position

It then increments the position indicator pos. If it has reached the end of the string, it resets pos to zero. Finally, the window.setTimeout() method is used to cause the ScrollMessage() function to execute again, using a timeout of one-fifth of a second.

This message-scrolling routine works fine, but it suffers from a failing common to most such routines: it obliterates anything else in the status line. This makes it hard to tell where the links go-in fact, it defeats the purpose of the friendly link messages created in the previous section.

To fix this, you'll define a new variable, showmsg. This variable will hold a Boolean value, initially true. When it is set to false, the ShowMessage() function will refrain from showing the message. Instead, it will set a timeout to show the message later. Here is the revised ShowMessage() function:

//flag to control message var showmsg = true; function ScrollMessage() { if (!showmsg) { window.setTimeout("ScrollMessage()",1500); showmsg = true; return; } window.status = msg.substring(pos, msg.length) + spacer + msg.substring(0, pos); pos++; if (pos > msg.length) pos = 0; // set timeout for next update window.setTimeout("ScrollMessage()",200); }

The additional code checks for a false value of the showmsg variable. If it is false, it uses the window.setTimeout() method to set a timeout for 1.5 seconds-plenty of time to read the description in the status bar.

To use this function, you will need to set showmsg to false in each one of the event handlers. To make this simpler, you use a function for the event handlers:

// Display a link help message function LinkMessage(text) { showmsg = false; window.status = text;

}

This function sets the showmsg variable to false, then displays the message in the status line. To call the function, you use an event handler like this:

onMouseOver="LinkMessage('This is the message');return true;"

You will need to change each of the links to use the new event handler syntax. Listing 8.6 shows the revised version of the FSC page, complete with both a scrolling message and helpful link messages. Figure 8.4 shows this page in Netscape with the message scrolling.

Figure 8.4 : The scrolling message example in Netscape.

Tip
As an alternative to scrolling messages, Chapter 11 includes a routine that displays random, nonscrolling tips, messages, or advertisements in the status line.


Listing 8.6. (SCROLMSG.asp) The FSC page with the scrolling message routine.
<HTML> <HEAD> <TITLE>Fictional Software Company</TITLE> <SCRIPT> // message to scroll in scrollbar var msg = "Welcome to Fictional Software Company. Watch for a new product coming next month!"; var spacer = "... ..."; // current message position var pos = 0; //flag to control message var showmsg = true; function ScrollMessage() { if (!showmsg) { window.setTimeout("ScrollMessage()",1500); showmsg = true; return; } window.status = msg.substring(pos, msg.length) + spacer + msg.substring(0, pos); pos++; if (pos > msg.length) pos = 0; // set timeout for next update window.setTimeout("ScrollMessage()",200); } // Start the scrolling message ScrollMessage(); // Display a link help message function LinkMessage(text) { showmsg = false; window.status = text; } </SCRIPT> </HEAD> <BODY> <IMG SRC="fsclogo.gif" alt="Fictional Software Company"> <HR> Welcome to our web page! Fictional Software Company specializes in creating innovative, user-friendly software applications with descriptions filled with industry buzzwords. <P> We have a wide range of products (3 of them) to meet the needs of you and your company. Follow the links below for more information. <P> <UL> <LI><A HREF="spread.asp" onMouseOver="LinkMessage('Information about the spreadsheet');return true;"> Fictional Spreadsheet 7.0</A> <LI><A HREF="word.asp" onMouseOver="LinkMessage('Information about the word processor');return true;"> Fictional Word Processor 6.0</A> <LI><A HREF="data.asp" onMouseOver="LinkMessage('Information about the database');return true;"> Fictional Database 7.0</A> </UL> <P> Unlike other software companies, our products have absolutely no bugs, and always work perfectly on all computers. Nevertheless, you may run into problems in rare cases, usually your own fault. If this happens, visit our <A HREF="support.asp" onMouseOver="LinkMessage('Technical Support for our products');return true;"> Technical Support</A> department for helpful information and tips. You can also view more information <A HREF="company.asp" onMouseOver="LinkMessage('Information about FSC Software Co.');return true;"> about our company</A> or order products with our friendly <a href="order.asp" onMouseOver="LinkMessage('Allows you to order products');return true;"> Order Form</A>. <HR> <I>(c)1998 FSC - designed by the FSC staff</I> </BODY> </HTML>

Using a Text Field to Scroll a Message

There are some disadvantages to using the status line to display scrolling messages. For one thing, the user may want to view URLs rather than your descriptions. Also, the browser uses it to display status when loading documents.

Finally, the status line is at the bottom of the page-hardly the place for an important announcement. Some users habitually ignore the status line, and may not even see your message.

To solve these problems, you can use a text field as an alternative to the status line. You can display help for links in such a field or use it to scroll a message.

Changing the ScrollMessage() function to use a text field instead of the status line requires only a minor change. Here is the revised function:

function ScrollMessage() { document.form1.text1.value = msg.substring(pos, msg.length) + spacer + msg.substring(0, pos); pos++; if (pos > msg.length) pos = 0; // set timeout for next update window.setTimeout("ScrollMessage()",200);

}

You are now placing the current message value in the value property of the text1 form element. Notice that the check for the showmsg variable is no longer necessary, because the scrolling message will not conflict with the link descriptions (which are still in the status line).

You define the text field (in its own little form) with the HTML:

<FORM name="form1"> <INPUT TYPE="text" name="text1" SIZE="60"> </FORM>

One more change is necessary. Because the form1 element doesn't actually exist until it is defined in the Web page, you can no longer start the scrolling in the <HEAD> section of the document. It must start after the page is loaded.

An easy way to accomplish this is with the document's onLoad event handler. You use the following <BODY> tag to start the document and define the event handler:

<BODY onLoad = "ScrollMessage();">

Note
One disadvantage of using a text field in this way is that the user can modify the value. However, because you're updating the field every fifth of a second, the user can't affect it much.

Listing 8.7 integrates the new function and the text field into the FSC home page. The status line is still used to display help about each of the links. Figure 8.5 shows Netscape's output of this page.

Figure 8.5 : Netscape shows the FSC home page with the scrolling text field.


Listing 8.7. (SCROLTXT.asp) The FSC page with the scrolling text field routine.
<HTML> <HEAD> <TITLE>Fictional Software Company</TITLE> <SCRIPT> // message to scroll in text field var msg = "Welcome to Fictional Software Company. Watch for a new product coming next month!"; var spacer = "... ..."; // current message position var pos = 0; //flag to control message function ScrollMessage() { document.form1.text1.value = msg.substring(pos, msg.length) + spacer + msg.substring(0, pos); pos++; if (pos > msg.length) pos = 0; // set timeout for next update window.setTimeout("ScrollMessage()",200); } // Display a link help message function LinkMessage(text) { window.status = text; } </SCRIPT> </HEAD> <BODY onLoad = "ScrollMessage();"> <IMG SRC="fsclogo.gif" alt="Fictional Software Company"> <FORM name="form1"> <INPUT TYPE="text" name="text1" SIZE="55"> </FORM> Welcome to our web page! Fictional Software Company specializes in creating innovative, user-friendly software applications with descriptions filled with industry buzzwords. <P> We have a wide range of products (3 of them) to meet the needs of you and your company. Follow the links below for more information. <P> <UL> <LI><A HREF="spread.asp" onMouseOver="LinkMessage('Information about the spreadsheet');return true;"> Fictional Spreadsheet 7.0</A> <LI><A HREF="word.asp" onMouseOver="LinkMessage('Information about the word processor');return true;"> Fictional Word Processor 6.0</A> <LI><A HREF="data.asp" onMouseOver="LinkMessage('Information about the database');return true;"> Fictional Database 7.0</A> </UL> <P> Unlike other software companies, our products have absolutely no bugs, and always work perfectly on all computers. Nevertheless, you may run into problems in rare cases, usually your own fault. If this happens, visit our <A HREF="support.asp" onMouseOver="LinkMessage('Technical Support for our products');return true;"> Technical Support</A> department for helpful information and tips. You can also view more information <A HREF="company.asp" onMouseOver="LinkMessage('Information about FSC Software Co.');return true;"> about our company</A> or order products with our friendly <a href="order.asp" onMouseOver="LinkMessage('Allows you to order products');return true;"> Order Form</A>. <HR> <I>(c)1998 FSC - designed by the FSC staff</I> </BODY> </HTML>

Workshop Wrap-Up

In this chapter, you learned some of the ways a Web page can be improved by using JavaScript, including the following:

  • Using selection lists to create a table of contents to make the page easy to navigate
  • Using the status line to display information about links rather than the URLs
  • Using the status line to display a scrolling message, and using a text field as an alternative for the purpose

Next Steps

To continue your studies of JavaScript, move on to one of the following chapters:

  • To learn the specifics about the objects and window elements used in this chapter, see Chapter 5 "Accessing Window Elements as Objects."
  • To continue improving a Web page, this time using advanced features such as frames, see Chapter 9 "Using Frames, Cookies, and Other Advanced Features."
  • To learn some techniques for organizing a larger and more complicated Web site, see Chapter 10, "Working with Multiple Pages and Data."
  • To see some more real-world examples of the techniques in this chapter, see Chapter 11, "Real-Life Examples II."

Q&A

Q:
What's wrong with the many popular scrolling message routines available on the Web?
A:
Most of them are victims of the memory leak bug in Netscape, because they reassign a string every time the text in the status bar moves. The example in this chapter avoids this problem. See Chapter 14, "Debugging JavaScript Programs," for details.
Q:
Is there any way to use some kind of "floating hints" or "balloon help" with links instead of using the status bar?
A:
Not currently. This may be added in some fashion in a future implementation of JavaScript.
Q:
Can the navigation bar in this chapter be used with browsers that don't support JavaScript?
A:
Yes. You could easily modify it to send the selections to a CGI script, which could send the user to the correct page. You'll take a closer look at CGI in Chapter 18.






|  About us | Categories | New Releases | Most Popular | Web Tutorial | Free Download | Drivers |



2013 Softlookup Corp. Privacy Statement