Other Neat Stuff

[ LiB ]

Other Neat Stuff

In the next several sections of this chapter, you will learn three very useful tricks. First, I will show you how easy it is to add a clock to your Web pages. A clock is especially useful if you create pages at which visitors are likely to spend a great deal of time. For example, you might write a page that reloads itself every few minutes so that you can provide your visitors with the real-time information you are positing on the Web site. Placing a digital clock on your pages enables your visitors to see how long they have been visiting as well as how current the existing information is.

The second example you will look at shows an option for working around one of JavaScript's main weaknesses: its inability to provide meaningful, password-protected access to your Web pages. This example shows you a way to apply a relatively simple password scheme that will suffice to keep the average unauthorized Web surfer away from your site.

Then I'll show you how to create your own banners. Banners provide a great way to advertise other parts of your site or to make money by leasing banner space to people who want to advertise on your Web pages.

Building a JavaScript Clock

Adding a digital clock to your Web pages is a relatively simple task. All it takes is the Date object and the setTimeout() method. You can create a clock in its most simple form by using the document.write() method to display the clock. However, this example adds a finishing touch by displaying the clock inside a form text field.

 <HTML>   <HEAD>     <TITLE> Script 4.15 - Building a JavaScript Clock</TITLE>     <SCRIPT LANGUAGE="JavaScript" TYPE="Text/JavaScript">     <!-- Start hiding JavaScript statements       function ShowClock() {         the_time_is = new Date;         the_minute = the_time_is.getMinutes();         the_hour = the_time_is.getHours();         the_second = the_time_is.getSeconds();         if (the_minute < 10) {           the_minute = "0" + the_minute;         }         if (the_hour < 10) {           the_hour = "0" + the_hour;         }         if (the_second < 10) {           the_second = "0" + the_second;         }         document.myForm.displayTime.value = the_hour + ":"  +           the_minute + ":" + the_second;         setTimeout("ShowClock()",1000);       }     // End hiding JavaScript statements -->     </SCRIPT>   </HEAD>    <BODY onLoad="ShowClock()">     <FORM NAME="myForm">       <B>The time is:</B>       <INPUT NAME="displayTime" TYPE="TEXT" SIZE="8">     </FORM>   </BODY> </HTML> 

This example places the script in the head section. The first thing the script does is to define a function named ShowClock() that is used to acquire, format, and display the clock's data.

The first thing the ShowClock() function does is to set the value of a variable named the_time_is to the current date. It then uses the getMinutes(), getHours() , and getSeconds() methods of the Date object to extract the individual elements of time:

 the_time_is = new Date the_minute = the_time_is.getMinutes() the_hour = the_time_is.getHours() the_second = the_time_is.getSeconds() 

To provide a consistent display, the script examines each element to make sure that it is two digits long. If the minute, hour , or second value is between 0 and 9, the script pads the value with a 0. Therefore 0 hours becomes 00 hours, 6 seconds becomes 06 seconds, and so on.

 if (the_minute < 10) {   the_minute = "0" + the_minute } if (the_hour < 10) {   the_hour = "0" + the_hour }  if (the_second < 10) {   the_second = "0" + the_second } 

After each element has been properly formatted, the script assembles and displays the elements in the text field displayTime on the form myForm as shown here:

 document.myForm.displayTime.value = the_hour + ":"  +   the_minute + ":" + the_second 

To keep the clock running, the ShowClock() function ends by scheduling its own execution in one second using the setTimeout() method:

 setTimeout("ShowClock()",1000) 

Figure 4.18 shows what this example looks like when you load the page.

Figure 4.18. Creating a simple digital clock

graphic/04fig18.gif


A Simple Password Script

As I have already stated, client-side JavaScript lacks the capability to implement a true password-protection scheme for a Web site. However, when used in conjunction with a Web server-based program, JavaScript can provide a front end that collects the user's name and password, sends the user 's information to the server program, and displays an HTML page that the server returns. Figure 4.19 shows this process. In this example, the server executes a CGI program that validates the user against a database and then returns an HTML page based on the success or failure of the validation process.

Figure 4.19. A depiction of a typical password validation process

graphic/04fig19.gif


By itself, a client-side JavaScript cannot accomplish this type of password validation. Of course, you could always write a script and embed user names and passwords in the code. Although this approach might stop some unwanted visitors, anyone who knows how to view HTML source code could read it and discover the names and passwords. To be a little more clever, you could place the user names and passwords in an external .js file, which would probably be enough to stop the average unauthorized user.

One trick you can use to provide a measure of password protection for your Web site is to publish an intermediary Web page that requires the visitor to provide a password before loading your site's real home page. The trick is to make the required password the same as the name of your home page.

Figure 4.20 shows an example in which the visitor finds his way to your intermediary page and is confronted by a password form. In this example, the user must enter ivworld in the Password field to gain access to the site. Of course, if users become aware that the password is the name of the site's real home page, they could just as easily load that page instead of opening the intermediary password page and typing the password. However, unless you provide your users with the password, they cannot find the page; if you gave the password to them, then it's probably okay for them to load the page directly anyway.

Figure 4.20. Requiring a password to access your Web site

graphic/04fig20.gif


Following is the script required to implement the example presented in Figure 4.21:

Figure 4.21. Password-protecting your Web site

graphic/04fig21.gif


 <HTML>   <HEAD>     <TITLE> Script 4.16 - A simple password-protection example </TITLE>     <SCRIPT LANGUAGE="JavaScript" TYPE="Text/JavaScript">     <!-- Start hiding JavaScript statements       function LoadTheURL() {         document.location.href = "http://www. xxxxxxxxxx.com/" +              document.myForm.psswdField.value + ".html";        }     // End hiding JavaScript statements -->     </SCRIPT>   </HEAD>   <BODY>     <B>Please type your password:</B>     <FORM NAME="myForm">       <INPUT NAME="psswdField" TYPE="password" size="15">       <INPUT NAME="Login" TYPE="button" VALUE="Login" onClick="LoadTheURL()">     </FORM>   </BODY> </HTML> 

NOTE

For the previous example to work, you need to change http://www.xxxxxxxx.com to the URL of a real Web site.

First a function named LoadTheURL() is defined in the head section. The function consists of one statement. The href property of the location object, a child of the document object, is set to the value of a URL address. This address is a concatenated string that includes the value of document.myForm.passwdField.value . This value contains the password typed by the user.

 function LoadTheURL() {   document.location.href = "http://www. xxxxxxxxxx.com/" +     document.myForm.psswdField.value + ".html"; } 

The value of document.myForm.passwdField .value is established in the page's form. The form is named myForm and contains two elements: The first element is a password field named passwdField . This field is similar to the text field you have seen in other form examples except that it automatically hides the characters as the user types them, thus hiding the password from prying eyes. The second form element is a button with an onClick event handler that calls the LoadTheURL() function when the button is clicked.

 <FORM NAME="myForm">   <INPUT NAME="psswdField" TYPE="password" size="15">   <INPUT NAME="Login" TYPE="button" VALUE="Login" onClick="LoadTheURL()"> </FORM> 

The result is that as soon as the script sets the document.location.href property, the browser tries to load the target URL. If the user types the wrong password, an error appears; otherwise your home page loads.

NOTE

This is a very simple script. In real life, you would probably want to add code that validates the content of the form before processing it. For example, you could make sure that the user does not leave the Password field blank.

Figure 4.21 shows what the preceding script looks like when it is loaded by the browser.

A Rotating Banner Example

This next example shows you one way to create a cycling banner on your Web site. In this case, the script cycles through four banners; the script can be easily modified to accommodate as many or as few banners as you want to display.

NOTE

An alternative to using JavaScript to create banners is to use a graphics application to create an animated GIF image that automatically cycles through a collection of GIF files. However,creating banners using JavaScript gives you several advantages over using animated GIFs: With JavaScript, you can easily adjust the behavior of the banner. With JavaScript, you can use JPEG files, which produce clearer images and are smaller than their GIF counterparts, making them download faster.You can bet that people who visit your Web site will appreciate that!

 <HTML>   <HEAD>     <TITLE> Script 4.17 - A Rotating Banner Example</TITLE>     <SCRIPT LANGUAGE="JavaScript" TYPE="Text/JavaScript">     <!-- Start hiding JavaScript statements       MyBannerArray = new Array(4);        MyBannerArray[0]="banner0.jpg";       MyBannerArray[1]="banner1.jpg";       MyBannerArray[2]="banner2.jpg";       MyBannerArray[3]="banner3.jpg";       current_banner=0;       no_of_banners=MyBannerArray.length;       function CycleBanner() {           if (current_banner==no_of_banners) {             current_banner=0;           }           document.myBanner.src=MyBannerArray[current_banner];           current_banner ++;           setTimeout("CycleBanner()", 5*1000);       }     // End hiding JavaScript statements -->     </SCRIPT>   </HEAD>   <BODY onLoad="CycleBanner()">     <CENTER> <IMG NAME="myBanner" SRC="banner0.jpg"> </CEN TER>   </BODY> </HTML> 

The first thing the script does is to define and populate an array named MyBannerArray with the four JPEG images files:

 MyBannerArray = new Array(4); MyBannerArray[0]="banner0.jpg"; MyBannerArray[1]="banner1.jpg"; MyBannerArray[2]="banner2.jpg"; MyBannerArray[3]="banner3.jpg"; 

Next, two variables are created. The first variable is used to track the currently selected element in the array. The second variable represents the total number of elements in the array:

 current_banner=0; no_of_banners=MyBannerArray.length; 

Then a function called CycleBanner() is created. It contains an if statement that compares the value of current_banner to no_of_banners . With each iteration of this function, the value of current_banner is increased by 1. When current_banner equals no_of_banners , every banner will have been displayed. The if statement then sets current_banner back to 0, thus preparing the next cycle of the banner rotation.

 if (current_banner==no_of_banners) {   current_banner=0; } 

The script then sets the image source for the myBanner image (document. myBanner.src) equal to the current banner (MyBannerArray [current_banner]) . Then it increments the value of current_banner to represent the next JPEG in the array:

 document.myBanner.src=MyBannerArray[current_banner]; current_banner++; 

The last thing the function does is to use the setTimeout() method to call itself again in 5 seconds, thus establishing an indefinite loop:

 setTimeout("CycleBanner()", 5*1000); 

NOTE

To ensure a smooth and attractive effect as the banners roll by, make sure that all the banner images have the same physical dimensions.

Figure 4.22 shows the result of loading this script in a browser. The first of four banners appears in the body of the page; it will be replaced in five seconds by the second image in the array.

Figure 4.22. Making money by renting banner space on your Web pages

graphic/04fig22.gif


[ LiB ]


Learn JavaScript In a Weekend
Learn JavaScript In a Weekend, Second Edition
ISBN: 159200086X
EAN: 2147483647
Year: 2003
Pages: 84

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