Writing Simple Scripts

Now that you have a general idea of how to write JavaScript code, you are ready to look at a few examples of how you can use JavaScript in your Web pages. In this section, you will learn how to hide and show page elements using JavaScript, how to access elements on a page and read and change their attributes, and how to check information entered into a form before it's submitted. These three tasks are the most common tasks taken on by JavaScript developers.

I have tested the scripts used in this section in Internet Explorer 6 and Netscape 7.1, but they are simple scripts that should work in earlier versions as well. As always, before you implement any scripting solution, you should thoroughly test it in all Web browsers you think your Web site visitors might be using.

NOTE

The finished pages and files for all these scripts are located in the CH24 folder on the CD accompanying this book.


Showing and Hiding Page Elements

One of the most common techniques in browser scripting is changing page content based on certain conditions, such as when the mouse pointer passes over a particular graphic. This type of effect is extremely easy to implement with FrontPage Behaviors, but you might find that you want to edit the code that FrontPage generates. You might also find that a FrontPage Behavior doesn't do exactly what you need and decide to implement your own script. In these cases, understanding how this type of effect is achieved with JavaScript is invaluable.

In this example, you will create a Web page with a list of links on the left side. When you pass over a link, text on the Web page will change to indicate the nature of the link you are pointing to. All of this will be accomplished using DHTML that is programmed using JavaScript.

  1. Create a new Web site or open an existing Web site.

  2. Create an empty Web page.

  3. Insert a table with 1 row and 2 columns, no border, and a width of 100%.

  4. Right-click on the left column and select Cell Properties.

  5. Check the Specify Width check box.

  6. Select the In Pixels option and enter 150 for the width.

  7. Click OK.

  8. Save your page.

The left column will contain links to parts of the Web site. When you hover over each link, text describing that link will appear in the right column of the table. To implement this, you will need to insert a div to hold the text description for each link. When you hover over a link, you will display the div for that link and hide all the other divs.

Enter the following items in the left column and press the Enter key after each item:

  • Home Page

  • Our Products

  • About Us

  • Contact Us

In a real-world Web site, you would link each of these to their respective pages in the Web site; but for now, simply link each one to the page you are currently editing so that you will have a hyperlink to work with.

Now you will need to create some <div> tags to hold the text for each link. To do this, you will use the Layers feature in FrontPage:

  1. Select Insert, Layer.

  2. Size and position the layer so that it appears in the right column of your table.

  3. Right-click the layer and select Copy.

  4. Right-click the layer again and select Paste.

  5. Right-click the layer and select Paste three more times so that there are four total layers one right on top of the other.

  6. Select View, Task Pane to show the task pane.

  7. Right-click the first layer and select Modify ID.

  8. Change the first layer's ID to Home.

  9. Change the second layer's ID to Products.

  10. Change the third layer's ID to About.

  11. Change the fourth layer's ID to Contact.

  12. Right-click the Home layer and select Set Visibility: Hidden.

  13. Repeat step 12 for the remaining layers.

  14. Save the page.

Your page should now look like the one shown in Figure 24.3.

Figure 24.3. The Web page is now ready for you to add some code.

graphics/24fig03.gif

TIP

FrontPage uses absolute positioning for layers. All the layers you inserted are stacked on top of each other. Therefore, any text added to each div will appear in the same place on the page because they each sit on their own layer at the same position on the page.


For more information on using Layers, see "Using Layers," p. 499.


When you make the layers hidden using the task pane, FrontPage simply adds a CSS property to the <div> tags to make them hidden. That property is the visibility property. For example, the following <div> tag is hidden:

 
 <div  style="visibility: hidden;">I am hidden.</div> 

When the Web page containing this <div> tag is loaded, the div will be invisible.

TIP

In situations in which a div is not absolutely positioned, hiding it using the visibility property makes it invisible, but the browser still reserves space for the div. The result is an empty area where the div is on the page. To prevent this, use the display property for a div that is not absolutely positioned. When the display property is set to none, the div will not be displayed and the browser will close up the space where the div used to be.


Enter some text for each layer that describes the content for that link. To do this, first click the layer in the Layers task pane and then click inside the layer. Enter any text you choose for each layer.

When someone visits your Web site, you want the text for the Home layer to be visible right away. If the site visitor then hovers over one of your other links, you want the layer for that link to be displayed. To do that, you will need to enter some code.

Switch to Code view and add the following JavaScript code before the closing </head> tag:

 
 <script language="javascript">   <!--   function hideAllDivs() {     document.getElementById('Home').style.visibility = 'hidden';     document.getElementById('Products').style.visibility = 'hidden';     document.getElementById('About').style.visibility = 'hidden';     document.getElementById('Contact').style.visibility = 'hidden';   }   function changeVisibility(layer) {     document.getElementById(layer).style.visibility = 'visible';     return true;   } //--> </script> 

For more information on entering code in Code view, see "Working in Code View and Split View," p. 519.


Two JavaScript functions exist in this code. The first one is the hideAllDivs function. This function sets the visibility property of each div to hidden. Remember that when you set the layer to be invisible, FrontPage set an inline style by adding a style attribute to the <div> tag. The value of that style attribute is visibility: hidden. To programmatically set an inline style on an element, you use the style attribute of the element. In the hideAllDivs function, you are setting an inline style for each div, and that inline style sets the visibility property to hidden.

The second function is the changeVisibility function. This function makes whatever layer name is passed to it visible by setting the visibility property to visible. For example, if you wanted to make the Products layer visible, you would call the changeVisibility function using the following code:

 
 changeVisibility('Products'); 

When the changeVisibility function is called with this line of code, the layer variable in the function is assigned the value Products, and the getElementById function then returns a reference to the Products layer on the page. The style attribute is then used to set the visibility property to visible.

Now you will need to add some code that will call these functions at the appropriate times to finish out the page. First, you will want to make sure that the Home layer is visible when the page is first loaded. To do that, you will call the changeVisibility function for the Home layer when the page loads.

Make sure that you're still in Code view and edit the <body> tag of your page so that it resembles the following code:

 
 <body onload="changeVisibility('Home');"> 

The onload event of the <body> tag is triggered automatically as soon as the page has finished loading. When an event is triggered, that event is said to have fired. By adding a call to the changeVisibility function in the onload event of the <body> tag, you cause the Home layer to become visible when the onload event is fired.

The final step is to edit the hyperlinks you created so that they cause the correct layers to appear and disappear as the mouse moves over them. To add this functionality, you will use two different events the onmouseover event and the onmouseout event. The onmouseover event is fired when the mouse moves over the element, and the onmouseout event is fired when the mouse moves off the element.

Locate the <a> tag for the Products link and edit it so that it resembles the following code:

 
 <a href="default.htm" onmouseover="hideAllDivs();changeVisibility('Products');" onmouseout="hideAllDivs();changeVisibility('Home');"> 

The onmouseover event first calls the hideAllDivs function. This causes any visible div to be hidden in preparation for displaying the Products layer. It then calls the changeVisibility function and passes Products to it. This causes the Products layer to become visible. Note that a semicolon appears between the two function calls.

When the mouse is moved off the Products link, the onmouseout event is fired. This event again calls the hideAllDivs function, which hides the Products layer. It then calls the changeVisibility function to make the Home layer visible again because we're on the home page.

To finish out the page, edit the About and Contact hyperlinks just as you did with the Products hyperlink. Make sure that you pass the correct layer name to the changeVisibility function in the onmouseover event. After you've finished editing your hyperlinks, save the page and preview it in your browser to see your layers swapped out as you hover over the hyperlinks.

graphics/troubleshooting_icon.jpg

If the divs don't change when you mouse over them, see "Divs Don't Change on Rollover" in the "Troubleshooting" section of this chapter.


Accessing and Changing Attributes

JavaScript code is often used to access attributes of HTML tags. Using JavaScript, you can read the value of a particular attribute and also change the value of an attribute. Web pages that use image swapping use this technique to change the image file that is displayed when the mouse hovers over an image. In this section, you will write some JavaScript code that will swap an image when your mouse hovers over it.

The HTML <img> tag has an attribute called src that specifies the image file to be displayed. By using JavaScript to change the src attribute of an image tag, you can easily create the effect of swapping the image with another image. To do this, you will need to perform two primary tasks preload the images and write the code to swap the images.

Before you get started, you will need a couple of images to work with. You can use the parrot_gray.jpg and the parrot_color.jpg images in the CH24/Swap folder on the CD accompanying this book, or you can use your own images. Just make sure that the images are the same size so that the rollover effect will work correctly. Save whatever images you decide to use into the images folder of your Web site.

Preloading Images

Your first step is to add a JavaScript to preload the images that will be swapped. You want to preload the images because if you don't, when your Web site visitors hover over your original image, they will have to wait for the browser to download the second image before the images are swapped. This delay can take several seconds on a dial-up Internet connection, and that delay makes your effect seem unprofessional.

Preloading images with JavaScript is an easy task. Open a new page and enter the following JavaScript code before the closing </head> tag:

 
 <script language="javascript">   <!--   grayImg = new Image();   grayImg.src="/books/2/138/1/html/2/images/parrot_gray.jpg";   colorImg = new Image();   colorImg.src="/books/2/138/1/html/2/images/parrot_color.jpg;   //--> </script> 

This code defines two variables called grayImg and colorImg. It then sets these variables equal to a new Image object. An Image object is an object that represents an HTML <img> tag. You then set the src attribute of the new Image object to the image file that you want to display for that object. After this code runs, you will have two Image objects one for the parrot_gray.jpg image (the initial image) and one for the parrot_color.jpg image.

Note that this code does not exist within a function call. That's because you want this code to run when the page loads. You could place this code within a JavaScript function and call it in the onload event of the <body> tag, but doing that would cause the script to run immediately after the page loads. If your Web site visitor were to mouse over the image as soon as the page finishes loading, you wouldn't get the benefit of the image preloading.

TIP

You can use the Preload Images Behavior to preload the images if you want. However, because I feel that understanding what goes on when you use that Behavior is important, I have included the code necessary to preload images.


Writing a Function to Swap Images

The next step is to write a function that will swap the images. Because this is a function that you might want to reuse in other Web pages, it makes sense to write it so that it isn't specific to the images you are using in this example. Instead, the function should be written as a generic function that can swap images based on the information passed to it.

Edit your script to include the swapImage function as follows:

 
 <script language="javascript">   <!--   grayImg = new Image();   grayImg.src="/books/2/138/1/html/2/images/parrot_gray.jpg";   colorImg = new Image();   colorImg.src="/books/2/138/1/html/2/images/parrot_color.jpg;   function swapImage(imgID, imgObj) {     if (document.images) {       document.images[imgID].src = imgObj.src;     }   }   //--> </script> 

The swapImage function takes two parameters imgID and imgObj. The imgID variable will contain the id attribute of the image that's being swapped. This allows you to refer to the correct page element. The imgObj variable is the object name for the image that you want to display in place of the original image. When the function runs, the src attribute of the original image is changed to the src attribute for the swapped image. Since the images have been preloaded, the result of this function is that the image instantly changes.

Adding the Images

Now the JavaScript code is in place. All that's left is to insert the original image into a new Web page and then add some JavaScript function calls to the <img> tag. Insert the parrot_gray.jpg image onto your page. Using the Quick Tag Editor, edit the <img> tag so that it appears as follows:

 
 <img border="0"  src="/books/2/138/1/html/2/images/parrot_gray.jpg" width="92" height="122" onmouseover="swapImage('parrot', colorImg);" onmouseout="swapImage('parrot', grayImg);"> 

For more information on the Quick Tag Editor, see "Editing Code with the Quick Tag Editor," p. 532.


The <img> tag now contains code for the onmouseover event that calls the swapImage function and passes 'parrot' and colorImg to it. This tells the JavaScript function that you are changing the image for the tag with an id attribute of parrot. It also tells the JavaScript function that you want to change the src attribute of the tag so that it's equal to the src attribute of the colorImg object. The src attribute of the colorImg object is set when the images are preloaded, so when the mouse hovers over the grayscale picture of the parrot, it changes automatically to a color picture right before your eyes. The onmouseout event calls the swapImage function again to change the images back again. Using this exact same procedure, you are now equipped to write your own JavaScript rollover buttons.

graphics/troubleshooting_icon.jpg

If there is a delay when the images swap, see "Images Don't Swap Instantly" in the "Troubleshooting" section of this chapter.


Form Field Validation

Another common use of JavaScript in Web pages is validation of form fields. In this section, you will write JavaScript that will validate an HTML form and make sure that data was entered in each form field. It will also check to ensure that only numeric characters are entered in a particular field and that no more than three digits are entered.

Creating the Form to Validate

First, you will need to create an HTML form that will be validated by your script:

  1. Create a new page in your Web site.

  2. Select Insert, Form, Textbox to insert a form and a textbox control.

  3. Insert another textbox control on the form under the first text box.

  4. Type the text Enter your name: above the first text box.

  5. Type the text Enter your age: above the second text box.

  6. Double-click the first text box and change the name to txtName.

  7. Double-click the second text box and change the name to txtAge.

  8. Save the page.

Your page should now resemble the page in Figure 24.4.

Figure 24.4. The finished HTML form that will be validated with JavaScript.

graphics/24fig04.gif

For more information on working with Forms, see "Using Forms," p. 359.


Adding the JavaScript Validation Function

Now you will need to enter some JavaScript code to validate the form. Here's the JavaScript function to validate both of the form fields.

 
 <script language="javascript">   function validateForm(theForm) {     var txtName;     var txtAge;     var nums = '0123456789';     txtName = theForm.elements[0];     txtAge = theForm.elements[1];     if ((txtName.value == '') || (txtAge.value == '')) {       alert('Please specify both your name and your age.');       return false;     }     for (var i = 0; i < txtAge.value.length; i++) {       if (nums.indexOf(txtAge.value.charAt(i)) == -1) {         alert('You can only specify numeric data for age.');         return false;       } else if (txtAge.value.length > 3) {         alert('You cannot possibly be that old.');         return false;       }     }     return true;   } </script> 

This script is the most complicated yet, but it's not quite as complex as it looks at first glance. The first three links set up three variables one for the txtName form field, one for the txtAge form fields, and one for the numeric characters you will validate the txtAge field against.

Next, you set the txtName and the txtAge variables equal to their respective form fields. To get a reference to each form field, you use the variable called theForm. This variable will hold a reference to whatever has been passed into the validateForm function. As you will see later, a reference to the form itself is passed to this function. The elements collection contains one object for each form field in the form. The first form field is called elements[0], the second elements[1], and so on. The first element in your form is the txtName form field, so the txtName variable is assigned to theForm.elements[0]. The txtAge variable is then assigned to theForm.elements[1], the txtAge form field.

Validating the Form Fields

Now that you have a reference to both the txtName and the txtAge form fields, you check to ensure that both of them contain data. You do this by checking to see if their value property is an empty string with the following line of code:

 
 if ((txtName.value == '') || (txtAge.value == '')) 

The value property returns the data entered into the from field. If the value property returns an empty string, you know that the user hasn't entered any data and you display an appropriate message using the alert method. (Notice that to check whether one value is equal to another value in JavaScript, you use double equal signs.) The double pipe symbol (||) is the logical OR operator in JavaScript. Therefore, if either txtAge or txtName contain no data, validation will fail.

The next validation to perform is checking whether the txtAge form field contains any non-numeric values. To do this, you use a string variable (nums) that contains all the valid numerical values. You then check each character in the txtAge form field against that string variable. Here is the code segment that performs that check:

 
 for (var i = 0; i < txtAge.value.length; i++) {   if (nums.indexOf(txtAge.value.charAt(i)) == -1) { 

The first line sets up a for loop. A for loop runs through a particular code segment repeatedly as long as a particular condition is met. When you define a for loop, you specify three items that control how the loop is executed a variable that will be used to indicate how many times the loop has run, a condition that must be met in order for the loop to continue running, and an incrementer for the loop counter that adds 1 to its present value each time the loop runs.

In the loop example, the variable that will indicate how many times the loop has run is called i, and it is initialized to 0 at the beginning of the loop. The condition is then specified so that as long as i is less than the length of whatever is entered into the txtAge form field, the code segment will continue to be executed. Finally, i is incremented with the i++ statement which adds 1 to its present value.

NOTE

The ++ symbol mean to increment the value to the left of it by 1. This syntax is used in many languages other than JavaScript, including C and C++. In fact, C++ got its name from the fact that its developers believed it to be one better than C.


When this code runs, the loop runs once for every character in the txtAge form field. Each time it runs, it checks a single character in the txtAge form field (using the charAt function) to see if it contains any value other than one of the numbers in the nums variable. It does this using the indexOf function. The indexOf function returns the position of one string within another string. If the string is not found, a value of -1 is returned. Each character in the txtAge form field should be found somewhere within the nums string variable. If it is not, you know it is not a numeric value and you display the appropriate message.

The final check is to determine if the length of the text entered into the txtAge form field exceeds three digits. If it does, you display a message letting the user know that he has lied about his age. If any of the previous validations fail, you return a value of false from the validateForm function because validation has failed. After a value is returned from a function, processing of that function stops. Therefore, the last line in the function returns a value of true because you know if you've gotten that far, validation has succeeded.

Adding the Call to the JavaScript Function

Now you need to add one final bit of code to make this all work. You need to add a call to the validateForm function. You do that in the onsubmit event of the form. Using the Quick Tag Editor, edit the <form> tag as follows:

 
 <form method="POST" action="--WEBBOT-SELF--" onsubmit="return validateForm(this);"> 

The onsubmit event fires when the form is submitted. In this event, you call the validateForm function and pass a reference to the form using the this keyword. The this keyword will always contain a reference to the particular element containing it. It is a convenient way to pass a reference to an element to a function. Because you have used return when calling the function, the return statement inside the validateForm function will return either true or false. If the value is false, the form will not be submitted. If the value is true, the form will submit as usual.

Save the page now and preview it in your browser. Submit the form without entering any data and see the result. Then enter your name in both fields and note that you are told that the txtAge form field can only contain numeric data. Then enter an age of 1000 and try to submit the form.

This is a simple validation script. In a real-world environment, you would want your validation script to be much more robust than this. However, this script gives you a solid foundation on the methods used when validating forms.



Special Edition Using Microsoft Office FrontPage 2003
Special Edition Using Microsoft Office FrontPage 2003
ISBN: 0789729547
EAN: 2147483647
Year: 2003
Pages: 443

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