Previous Page toc Index Next Page

Chapter 43

Building JavaScript applications

With JavaScript, there are many types of applications that can be created. JavaScript offers a wide collection of tools for you to create a variety of applications and to add interactive content to your World Wide Web pages. JavaScript also enables you to add greater usability to your forms by providing feedback when something is left blank or entered incorrectly. In addition, JavaScript can increase the amount of direct feedback users receive when visiting your site.

Introducing the Possibilities

Some of the possibilities with JavaScript are instant user feedback when a user moves over an object, enters a new section, or even when a user leaves your site. When using forms, the user can be given much more descriptive warnings and messages about what they have done incorrectly, and because JavaScript runs on the client, the user can keep trying to fill out the form without making a single request to your server.

Another possibility with JavaScript is building a system for automatic language translation. With JavaScript, it is possible to detect who your user is, given that they have previously “signed on,” and have your site’s output be in a language that is suited to that visitor.

Spell checking is another possibility. With JavaScript, you could set up a form that automatically spell checks all entries before they are submitted. The possible applications are limitless; from context-sensitive help to college financial planners, JavaScript enables you to add a level of interaction that is orders of magnitude greater than HTML, and you can achieve this without any complicated programming.

This section covers four JavaScript examples in detail. Each program is broken into small sections, and each section is discussed. At the end of the section, the source code is reprinted in its entire form for convenience. These examples give a good overview of the possibilities and uses of JavaScript in practical, everyday situations on the Web. All of these examples are available on the CD-ROM as well as on Live Software’s JavaScript Resource Center on the World Wide Web at http://jrc.livesoftware.com/.

Your First Example: Messages to the User

This first example demonstrates JavaScript’s capability to interact with the user. JavaScript has two built-in objects for directly communicating with the user; they are the alert() object and the confirm() object. In addition, JavaScript allows for the specification of a message that is displayed in the Netscape Navigator status bar. This enables you to display a context-sensitive message to the user without disrupting the display. The following example includes a demonstration of context-sensitive messages.

To begin your JavaScript file, start with the standard HTML header tags:

<HTML>

<HEAD>

Immediately following the <HEAD> tag, you should specify the beginning of your JavaScript functions by using the <SCRIPT> tag. In this example, we don’t use any functions, so the tag is not necessary here. We will include the tags as placeholders for future expansion. There are two commented lines between the tags describing the program. You may use this space for copyright information, author information, or whatever you wish.

<SCRIPT>

     // JavaScript Form Validation Demo

     // by Paul Colton

</SCRIPT>

Notice that the preceding comments use the single-line comment notation, the double forward slashes (//).

Before closing the <HEAD> tag, you should place the title of the page here. In this example, we use JavaScript User Messages.

<TITLE>JavaScript User Messages</TITLE>

</HEAD>

Next we open the <BODY> tag. In this example, we set a background color to white and the text color to black. The <BODY> tag is followed by a title and a small picture.

<BODY BGCOLOR=FFFFFF TEXT=000000>

<CENTER>

<FONT SIZE=+2>JavaScript’s User Messages</FONT><BR>

<IMG WIDTH=108 HEIGHT=26 SRC=”../images/previewercredit.gif”>

</CENTER>

The next section is a short description of what this demo tries to demonstrate. Some of the tags such as <HR> and <SMALL> are purely cosmetic.

<HR>

<SMALL>

Following are examples of different ways to send a message to a user.

Click on the links to see what actions they perform. Some links may

perform without clicks!<BR>

</SMALL>

<HR>

<FONT SIZE=+2><UL>

This next section begins to add some new tags that you normally would not see in a standard HTML page. These are the event handlers that JavaScript recognizes in order to perform specific actions. For example, the next line uses the onClick( ) event handler. This event is triggered when the user clicks on the link with their pointer. In this case, the event would call the object alert( ) and pass it the parameter Thank you!. Notice that the onClick( ) tag requires its parameters to be in quotes. If any of these parameters needs quotes, such as the alert() function, you must use single quotes in place of double quotes. This ensures that your browser properly recognizes the parameter list.

<LI><A HREF=”index.html” onClick=”alert(‘Thank you!’)”>Please click me.</A>

<P><UL>

When the link is clicked, a window pops up with the message specified. Figure 43.1 illustrates this.

Figure FIGURE 43.1.

JavaScript alert ( ) object.

The next set of lines contains a little more JavaScript code than the previous set. Notice that in these lines, the onClick( ) event handler contains several statements. As a matter of fact, the onClick( ) handler contains an if...else statement right in the <A HREF> tag. This example uses the other JavaScript message object, the confirm( ) object. This object is similar to alert( ), but it gives the user a choice of responses rather than a single OK button. In this example, the user may click OK or Cancel, each delivering its own alert( ) response.

<LI><A HREF=”index.html” onClick=”

     if(confirm(‘Are you sure about this?’))

          alert(‘Confidence is a great thing!’);

     else

          alert(‘Maybe next time, hang in there.’);”>A question for you.</A>

<P><UL>

Figure 43.2 illustrates the confirm( ) object as used in the preceding example.

Figure FIGURE 43.2.

The JavaScript confirm ( ) object.

This next section demonstrates the use of context-sensitive messages in the Navigator status bar. The first five letters of the alphabet are displayed. When your mouse pointer is moved over them, they trigger the specified onMouseOver( ) event handler, which sets the status bar to a short message describing the letter. The statement for setting the status bar in JavaScript is: self.status=”string”.

<LI>Check the status bar:

<A HREF=”index.html” onMouseOver=”self.status=’A is for Apple’;return true”>A</A>

<A HREF=”index.html” onMouseOver=”self.status=’B is for Boy’;return true”>B</A>

<A HREF=”index.html” onMouseOver=”self.status=’C is for Cool’;return true”>C</A>

<A HREF=”index.html” onMouseOver=”self.status=’D is for Dog’;return true”>D</A>

<A HREF=”index.html” onMouseOver=”self.status=’E is for Elephant’;return true”>E</A>

<P><UL>

Figure 43.3 illustrates the preceding example.

The final section in this example shows how you can use the onMouseOver( ) event handler for displaying an alert( ) or confirm( ) message. If the mouse pointer is moved over the link, you do not need to click the link; an alert( ) window opens with a short message. This could be used to warn a user of a potential problem associated with selecting the link.

Figure FIGURE 43.3.

Setting the Navigator status bar with onMouseOver ( ).

<LI><A HREF=”index.html” onMouseOver=”alert(‘You’re a little too close!’)”>Don’t Âget near me!</A><P>

</UL></UL></UL></UL>

</FONT><P><HR>

</BODY></HTML>

Figure 43.4 illustrates the preceding example.

Figure FIGURE 43.4.

Using onMouseOver ( ) with an alert ( ) object.

Listing 43.1 is the complete HTML source for the previous example.

<HTML><HEAD>

<SCRIPT>

// JavaScript Form Validation Demo

// by Paul Colton

</SCRIPT>

<TITLE>JavaScript User Messages</TITLE>

</HEAD>

<BODY BGCOLOR=FFFFFF TEXT=000000>

<CENTER>

<FONT SIZE=+2>JavaScript’s User Messages</FONT><BR>

<IMG WIDTH=108 HEIGHT=26 SRC=”../images/previewercredit.gif”>

</CENTER>

<HR>

<SMALL>

Following are examples of different ways to send a message to a user.

Click on the links to see what actions they perform. Some links may

perform without clicks!<BR>

</SMALL>

<HR>

<FONT SIZE=+2>

<UL>

<LI><A HREF=”index.html” onClick=”alert(‘Thank you!’)”>Please click me.</A><P>

<UL>

<LI><A HREF=”index.html” onClick=”if(confirm(‘Are you sure about this?’)) Âalert(‘Confidence is a great thing!’); else alert(‘Maybe next time, hang in Âthere.’);”>A question for you.</A><P>

<UL>

<LI>Check the status bar:

<A HREF=”index.html” onMouseOver=”self.status=’A is for Apple’;return true”>A</A>

<A HREF=”index.html” onMouseOver=”self.status=’B is for Boy’;return true”>B</A>

<A HREF=”index.html” onMouseOver=”self.status=’C is for Cool’;return true”>C</A>

<A HREF=”index.html” onMouseOver=”self.status=’D is for Dog’;return true”>D</A>

<A HREF=”index.html” onMouseOver=”self.status=’E is for Elephant’;return true”>E</A><P>

<UL>

<LI><A HREF=”index.html” onMouseOver=”alert(‘You\’re a little too close!’)”>Don’t Âget near me!</A><P>

</UL></UL></UL></UL>

</FONT><P><HR>

</BODY></HTML>

Form Validation: A Correct Form, the First Time

This next example is perhaps one of the most widely-used facilities of JavaScript: the capability to verify and check form input before it is submitted to the server. The following example consists of three form fields: a name field, an e-mail field, and a phone number field. Figure 43.5 is a view of the three fields.

The following example performs three specific types of checks on this form. First, it makes sure that all three fields are not left blank. Second, it makes sure that the e-mail field value contains the @ symbol somewhere in the field. Finally, the phone number is checked to make sure it contains only digits and that it is only either 10 or 12 digits. It will also automatically add the dashes for the user after the phone number has been entered. The full source, with all tags, is included at the end of the section.

This form-validation example uses several JavaScript functions in order to perform its validation checks on the form. The first and most important function is the submit_page() function. It is called when the user clicks the submit button to submit all the entered information. This function is responsible for calling the other remaining functions.

Figure FIGURE 43.5.

A Web form with name, e-mail, and phone fields.

<SCRIPT>

    // JavaScript Form Validation Demo

    // by Paul Colton

    function submit_page(form) {

The following statement creates a variable called foundError. Notice how the var keyword is used. This variable keeps track of whether the program has found any mistakes with the form submissions.

var foundError = false;

Here we call the isFieldBlank( ) function. (This function is defined later in the code.) This function returns true if the name field is blank. Otherwise it returns false. Notice in Figure 43.6 that if the name field is blank, an alert( ) is used to let the user know.

// Make sure the name field is not blank

if(isFieldBlank(form.name)) {

    alert(“You left the Name field blank.”);

    foundError = true;

}
Figure FIGURE 43.6.

The alert ( ) window when a field is left blank.

Here we call the isFieldBlank( ) function again to check if the e-mail field is blank.

// Make sure the email field is not blank

if(!foundError && isFieldBlank(form.email)) {

    alert(“You left the Email field blank.”);

    foundError = true;

}

We now check our final field with the isFieldBlank() function to see if the phone field is blank. Each time, if an error is found, the user is immediately alerted.

// Make sure the phone field is not blank

        if(!foundError && isFieldBlank(form.phone)) {

            alert(“You left the Phone field blank.”);

            foundError = true;

        }

If the program makes it this far, we now know that there is something in all of the fields. Another function is now called, the isValidEmail( ) function. This function checks for the presence of the “@” symbol. If it does not exist, the user is alerted. If it is there, the code moves on to the next check, the phone number check.

// Now make sure the email is valid

if(!foundError && !isValidEmail(form.email)) {

    alert(“You did not enter a valid email address.”);

    foundError = true;

}

The last check the program makes ensures the phone number is valid. It first checks to see if the correct number of digits are present, and then it makes sure they are all numbers. If there is no error, dashes are automatically added to the phone number (see Figure 43.7), and we proceed.

// If we don’t alredy have an error, check the phone number

if(!foundError && !isValidPhoneNumber(form.phone)) {

    alert(“You did not enter a valid phone number.”);

    foundError = true;

}
Figure FIGURE 43.7.

Dashes are automatically added to the phone number.

If by this time there is still no error, no errors have occurred. The program now prints a thank- you message that indicates a successful form submission. (See Figure 43.8.)

        if(!foundError) {

            document.open();

            document.write(“<HTML><HEAD><TITLE>Form Verification Demo</TITLE><            ÂHEAD>”);

            document.write(“<BODY BGCOLOR=FFFFFF TEXT=000000><CENTER>”);

            document.write(“<H1>Thank you for your submission.</H1>”);

            document.write(“</CENTER></BODY></HTML>”);

            document.close( );

        }

    }
Figure FIGURE 43.8.

A successful form submission after validation.

The other functions used in this form are listed at the end of the section.

Now we proceed to the actual form. Notice that the input fields do not contain any JavaScript tags.

<FORM NAME=”verifyInputDemo” METHOD=”get”>

Name : <INPUT TYPE=”text” NAME=”name” SIZE=50>

Email : <INPUT TYPE=”text” NAME=”email” SIZE=50>

Phone : <INPUT TYPE=”text” NAME=”phone” SIZE=50>

The submit button, on the other hand, contains the onClick() event handler. Notice that the event handler calls the function we reviewed previously, submit_page(). It also passes as a parameter this.form. This tells the function where to get the information about the form field values.

<INPUT TYPE=”button” NAME=”Submit” VALUE=”Submit Form” onClick=”submit_page(this.form)”>

Following is the complete source listing to the preceding example.

<HTML>

<HEAD>

<TITLE>Form Verification Demo</TITLE>

<SCRIPT>

    // JavaScript Form Validation Demo

    // by Paul Colton

    function submit_page(form) {

        var foundError = false;

        // FIRST CHECK FOR BLANK FIELDS

        // Make sure the name field is not blank

        if(isFieldBlank(form.name)) {

            alert(“You left the Name field blank.”);

            foundError = true;

        }

        // Make sure the email field is not blank

        if(!foundError && isFieldBlank(form.email)) {

            alert(“You left the Email field blank.”);

            foundError = true;

        }

        // Make sure the phone field is not blank

        if(!foundError && isFieldBlank(form.phone)) {

            alert(“You left the Phone field blank.”);

            foundError = true;

        }

        // NOW LET’S CHECK THAT THE FIELDS ARE VALID

        // Now make sure the email is valid

        if(!foundError && !isValidEmail(form.email)) {

            alert(“You did not enter a valid email address.”);

            foundError = true;

        }

        // If we don’t already have an error, check the phone number

        if(!foundError && !isValidPhoneNumber(form.phone)) {

            alert(“You did not enter a valid phone number.”);

            foundError = true;

        }

        if(!foundError) {

            document.open();

            document.write(“<HTML><HEAD><TITLE>Form Verification Demo</TITLE></               ÂHEAD>”);

            document.write(“<BODY BGCOLOR=FFFFFF TEXT=000000><CENTER>”);

            document.write(“<H1>Thank you for your submission.</H1>”);

            document.write(“</CENTER></BODY></HTML>”);

            document.close();

        }

    }

    // Check for a blank field

    function isFieldBlank(theField) {

        if(theField.value.length == 0)

            return true;

        else

            return false;

    }

    // Check for a valid email address (Does it contain a “@”)

    Âfunction isValidEmail(theField) {

        var foundSymbol = false;

        for(var i=0; i<theField.value.length; i++) {

            var ch = theField.value.substring(i,i+1)

            if (ch == “@”)

                foundSymbol=true;

        }

        return foundSymbol;

    }

    // Check that a phone number has the correct number of digits

    Âfunction isValidPhoneNumber(theField) {

        var inStr = theField.value;

        var inLen = inStr.length;

        // If this is a ten digit number XXXYYYZZZZ

        if(inLen == 10) {

            for(var i=0; i<inLen; i++) {

                var ch = inStr.substring(i,i+1)

                if (ch < “0” || “9” < ch)

                    return false;

            }

            var  fixedNumber = inStr.substring(0,3)

                    + “-”

                    + inStr.substring(3,6)

                    + “-”

                    + inStr.substring(6,10) ;

            theField.value = fixedNumber;

            alert(“Reformatted the Phone field to ‘“ + fixedNumber + “‘.”);

            return true;

        }

        // Is this is a twelve digit number WWXXXYYYZZZZ

        if (inLen == 12) {

            /* check country code */

            for (var i = 0; i < 2; i++) {

                var ch = inStr.substring(i,i+1)

                if (ch < “0” || “9” < ch)

                    return false;

            }

            /* check area code */

            for (var i = 2; i < 5; i++) {

                var ch = inStr.substring(i,i+1)

                if (ch < “0” || “9” < ch)

                    return false;

            }

            /* check prefix */

            for (var i = 5; i < 8; i++) {

                var ch = inStr.substring(i,i+1)

                if (ch < “0” || “9” < ch)

                    return false;

            }

            /* check body */

            for (var i = 8; i < 12; i++) {

                var ch = inStr.substring(i,i+1)

                if (ch < “0” || “9” < ch)

                    return false;

            }

            var  fixedNumber = inStr.substring(0,2)

                    + “-”

                    + inStr.substring(2,5)

                    + “-”

                    + inStr.substring(5,8)

                    + “-”

                    + inStr.substring(8,12) ;

            theField.value = fixedNumber;

            alert(“Reformatted the Phone field to ‘“ + fixedNumber + “‘.”);

            return true;

        }

        return false;

    }

</SCRIPT>

</HEAD>

<BODY BGCOLOR=FFFFFF TEXT=000000>

<CENTER>

<FONT SIZE=+2>JavaScript Form Verification Demo 3</FONT><BR>

<IMG WIDTH=108 HEIGHT=26 SRC=”../images/previewercredit.gif”>

</CENTER>

<HR>

<SMALL>

In addition to checking if a form field has been left blank, this example will try to ensure

that your email address is somewhat valid.<BR>

</SMALL>

<HR>

<FORM NAME=”verifyInputDemo” METHOD=”get”>

<B><PRE>

 Name : <INPUT TYPE=”text” NAME=”name” SIZE=50>

Email : <INPUT TYPE=”text” NAME=”email” SIZE=50>

Phone : <INPUT TYPE=”text” NAME=”phone” SIZE=50>

</PRE></B>

<CENTER>

<INPUT TYPE=”button” NAME=”Submit” VALUE=”Submit Form” onClick=”submit_page(this.form)”>

</CENTER>

</FORM>

<HR>

</BODY></HTML>

Interactive Forms: A Loan Planner

This example illustrates some of the more interactive uses for JavaScript. This application, based on a Netscape demonstration application, calculates the principal or monthly payments for a loan when you specify the number of payments and the interest rate. The example uses several of the event handlers to handle user input. In addition, it also uses the Math object to perform its calculations. Figure 43.9 shows the Loan Planner’s interface.

Figure FIGURE 43.9.

The Loan Planner interface.

This example also contains several functions, which are responsible for performing the calculations based on the user input. The following function, checkNumber(), checks to see if the input value is made up of entirely digits and gives an alert() if the value does not.

function checkNumber(input, min, max, msg) {

        msg = msg + “ field has invalid data: “ + input.value;

        var str = input.value;

        for (var i = 0; i < str.length; i++) {

            var ch = str.substring(i, i + 1)

            if ((ch < “0” || “9” < ch) && ch != ‘.’) {

                alert(msg);

                return false;

            }

        }

        var num = 0 + str

This next section verifies that the numbers are within range for the given field.

if (num < min || max < num) {

    alert(msg + “ not in range [“ + min + “..” + max + “]”);

    return false;

}

input.value = str;

return true;

}

The next several functions are responsible for computing the missing field. In other words, if you enter the principal, it computes monthly payments. If you enter the monthly payments, it computes the principal.

function computeField(input) {

     if (input.value != null && input.value.length != 0)

         input.value = “” + eval(input.value);

     computeForm(input.form);

}

function computeForm(form) {

    if ((form.payments.value == null || form.payments.value.length == 0) ||

        (form.interest.value == null || form.interest.value.length == 0) ||

        (form.principal.value == null || form.principal.value.length == 0)) {

        return;

    }

    if (!checkNumber(form.payments, 1, 480, “# of payments”) ||

        !checkNumber(form.interest, .001, 99, “Interest”) ||

        !checkNumber(form.principal, 100, 10000000, “Principal”)) {

        form.payment.value = “Invalid”;

        return;

    }

This section takes care of actually performing the calculations for the Loan Planner.

   var i = form.interest.value;

   if (i > 1.0) {

       i = i / 100.0;

       form.interest.value = i;

   }

   i /= 12;

   var pow = 1;

   for (var j = 0; j < form.payments.value; j++)

       pow = pow * (1 + i);

   form.payment.value = (form.principal.value * pow * i) / (pow - 1)

}

This function clears all fields on the screen.

function clearForm(form) {

    form.payments.value = “”;

    form.interest.value = “”;

    form.principal.value = “”;

}

The Loan Planner interface is built around a table. Within that table, the fields exist for the form. Notice that all the fields contain an onChange( ) event handler that called the computeField( ) function. When entering values, you can hit the Tab key to proceed to the next field. JavaScript automatically updates the field on which you were just working.

<TD><INPUT TYPE=TEXT NAME=payments  SIZE=5 onChange=computeField(this)> </TD>

<TD><INPUT TYPE=TEXT NAME=interest  SIZE=6 onChange=computeField(this)> </TD>

<TD><INPUT TYPE=TEXT NAME=principal SIZE=9 onChange=computeField(this)> </TD>

<TD> </TD>

<TD><INPUT TYPE=TEXT NAME=payment   SIZE=9 onChange=computeField(this)> </TD>

When the user is ready to compute, the onClick() event handler calls the computeForm() function to perform all the calculations.

<INPUT TYPE=”button” VALUE=”Compute”        onClick=computeForm(this.form)>

<INPUT TYPE=”reset”  VALUE=”Clear Fields”   onClick=clearForm(this.form)> </TD>

Figure 43.10 shows a completed form with actual numbers computed and inserted by JavaScript.

Figure FIGURE 43.10.

A completed Loan Planner form.

<HTML>

<HEAD>

<TITLE>JavaScript Loan Calculator</TITLE>

<SCRIPT LANGUAGE=”LiveScript”>

    // JavaScript Loan Calculator

    // by Paul Colton

    // based on a demo by Netscape Communications, Inc.

function checkNumber(input, min, max, msg) {

        msg = msg + “ field has invalid data: “ + input.value;

        var str = input.value;

        for (var i = 0; i < str.length; i++) {

            var ch = str.substring(i, i + 1)

            if ((ch < “0” || “9” < ch) && ch != ‘.’) {

                alert(msg);

                return false;

            }

        }

        var num = 0 + str

        if (num < min || max < num) {

            alert(msg + “ not in range [“ + min + “..” + max + “]”);

            return false;

        }

        input.value = str;

        return true;

    }

    function computeField(input) {

        if (input.value != null && input.value.length != 0)

            input.value = “” + eval(input.value);

        computeForm(input.form);

    }

    function computeForm(form) {

        if ((form.payments.value == null || form.payments.value.length == 0) ||

            (form.interest.value == null || form.interest.value.length == 0) ||

            (form.principal.value == null || form.principal.value.length == 0)) {

            return;

        }

        if (!checkNumber(form.payments, 1, 480, “# of payments”) ||

            !checkNumber(form.interest, .001, 99, “Interest”) ||

            !checkNumber(form.principal, 100, 10000000, “Principal”)) {

            form.payment.value = “Invalid”;

            return;

        }

        var i = form.interest.value;

        if (i > 1.0) {

            i = i / 100.0;

            form.interest.value = i;

        }

        i /= 12;

        var pow = 1;

        for (var j = 0; j < form.payments.value; j++)

            pow = pow * (1 + i);

        form.payment.value = (form.principal.value * pow * i) / (pow - 1)

    }

    function clearForm(form) {

        form.payments.value = “”;

        form.interest.value = “”;

        form.principal.value = “”;

    }

</SCRIPT>

<TITLE>JavaScript Loan Calculator</TITLE>

</HEAD>

<BODY BGCOLOR=FFFFFF TEXT=000000>

<CENTER>

<FONT SIZE=+2>JavaScript Loan Calculator</FONT><BR>

<IMG WIDTH=108 HEIGHT=26 SRC=”../images/previewercredit.gif”><BR>

<SMALL>(Based on a demo from Netscape)</SMALL>

</CENTER>

<HR>

<SMALL>

In this JavaScript example, you can find out just how much that new

house or car is going to cost you each month. Enter values in the fields below

to find out how much your payments would be with the given

number of payments, interest rate, and amount of the loan.<BR>

</SMALL>

<HR>

<CENTER>

<FORM method=POST>

<TABLE border=4>

<TR>

<TD><DIV ALIGN=CENTER>  # of<br>Payments</DIV></TD>

<TD><DIV ALIGN=CENTER>Interest<br>Rate</DIV></TD>

<TD><DIV ALIGN=CENTER>Principal</DIV></TD>

<TD> </TD>

<TD><DIV ALIGN=CENTER> Monthly<br> payment</DIV></TD>

</TR>

<TR>

<TD><INPUT TYPE=TEXT NAME=payments  SIZE=5 onChange=computeField(this)> </TD>

<TD><INPUT TYPE=TEXT NAME=interest  SIZE=6 onChange=computeField(this)> </TD>

<TD><INPUT TYPE=TEXT NAME=principal SIZE=9 onChange=computeField(this)> </TD>

<TD> </TD>

<TD><INPUT TYPE=TEXT NAME=payment   SIZE=9 onChange=computeField(this)> </TD>

</TR>

<TR>

<TD ALIGN=”center” COLSPAN=5>

<INPUT TYPE=”button” VALUE=”Compute”        onClick=computeForm(this.form)>

<INPUT TYPE=”reset”  VALUE=”Clear Fields”   onClick=clearForm(this.form)> </TD>

</TR>

</FORM>

</TABLE>

</FORM>

</CENTER>

<P><HR>

</BODY></HTML>

Creating New Windows: An Image Previewer

The final example in this chapter demonstrates how to open new windows and build your own custom content in those windows. The example illustrates a simple image previewer that uses JavaScript. Given a selection of images, the user can choose to select the preview button to open a smaller, separate window to view the image. The user can then select other images and browse through them without closing the preview window. Figure 43.11 shows the Image Previewer interface.

Figure FIGURE 43.11.

The Image Previewer interface.

The source code begins with a function named select_item( ). This is actually a C++ type constructor for a select_item( ) object. This object is used to decode the <SELECT> form field.

function select_item(name, value) {

        this.name = name;

        this.value = value;

    }

This next function is the one actually responsible for decoding the contents of the <SELECT> field. The function runs through all of the SELECT items and checks to see which one was selected by the user. It then returns a select_item() object to the caller.

function get_selection(select_object) {

    contents = new select_item();

    for(var i=0;i<select_object.options.length;i++)

        if(select_object.options[i].selected == true) {

            contents.name = select_object.options[i].text;

            contents.value = select_object.options[i].value;

        }

    return contents;

}

This function is responsible for actually building the new page and filling it with the preview image.

function display_image(formfield) {

    selection = get_selection(formfield.imagename);

Notice the following line; it opens a new window, setting many of the window properties as it opens.

myWindow = window.open(“”, “Preview”, “toolbar=0,location=0,directories=0,status=0,menubar=0,

scrollbars=0,resizable=0,copyhistory=0,width=200,height=255");

Note that the third parameter in the window.open() statement has been broken into two lines in order to fit on the page. In the final JavaScript code, this line should be one continuous line with no breaks within the quotes.

The current available properties are as follows:

These properties control which portions of the Navigator window you want visible. In this example, we will turn all the options off. Figure 43.12 shows the Image Previewer alongside the preview window.

Here, using document.write(), we will write in the HTML code necessary for creating our preview image. Notice that we must first call document.open() before writing to the window:

myWindow.document.open();

myWindow.document.write(“<HTML><HEAD>”);

myWindow.document.write(“<TITLE>Preview</TITLE>”);

myWindow.document.write(“</HEAD><BODY BGCOLOR=FFFFFF TEXT=000000>”);

myWindow.document.write(“<FORM><CENTER><B><FONT SIZE=+1>” +

    Âselection.name + “</FONT></B><HR>”);

myWindow.document.write(“<IMG HSPACE=0 VSPACE=0 HEIGHT=150 WIDTH=150 “ +

    ÂSRC=’http://jrc.livesoftware.com/ip/” + selection.value + “‘>”);
Figure FIGURE 43.12.

The Image Previewer preview window.

The next line is responsible for creating the close button in the preview window. It uses an onClick() event handler and calls window.close() directly when the button is pushed. This will close the preview window.

    myWindow.document.write(“<HR><FORM><INPUT TYPE=’button’ VALUE=’Close’ “ +

        “onClick=’window.close()’></FORM>”);

    myWindow.document.write(“</CENTER>”);

    myWindow.document.write(“</BODY></HTML>”);

    myWindow.document.close();

}

The following line is the “Preview Image” button. It uses the onClick() event handler to call the display_image() function.

<input type=button value=”Preview Image” onClick=”display_image(this.form)”>
<HTML>

<HEAD>

<SCRIPT>

    // JavaScript Image Preview Demo

    // by Paul Colton

    function select_item(name, value) {

        this.name = name;

        this.value = value;

    }

    function get_selection(select_object) {

        contents = new select_item();

        for(var i=0;i<select_object.options.length;i++)

            if(select_object.options[i].selected == true) {

                contents.name = select_object.options[i].text;

                contents.value = select_object.options[i].value;

            }

        return contents;

    }

    function display_image(formfield) {

        selection = get_selection(formfield.imagename);

        myWindow = window.open(“”, “Preview”, “toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0,Âcopyhistory=0,width=200,height=255”);

        myWindow.document.open();

        myWindow.document.write(“<HTML><HEAD>”);

        myWindow.document.write(“<TITLE>Preview</TITLE>”);

        myWindow.document.write(“</HEAD><BODY BGCOLOR=FFFFFF TEXT=000000>”);

        myWindow.document.write(“<FORM><CENTER><B><FONT SIZE=+1>” +

            selection.name + “</FONT></B><HR>”);

        myWindow.document.write(“<IMG HSPACE=0 VSPACE=0 HEIGHT=150 WIDTH=150 “ +

            “SRC=’http://jrc.livesoftware.com/ip/” + selection.value + “‘>”);

        myWindow.document.write(“<HR><FORM><INPUT TYPE=’button’ VALUE=’Close’ “ +

            “onClick=’window.close()’></FORM>”);

        myWindow.document.write(“</CENTER>”);

        myWindow.document.write(“</BODY></HTML>”);

        myWindow.document.close();

    }

</SCRIPT>

<TITLE>JavaScript Image Previewer Demo</TITLE>

</HEAD>

<BODY BGCOLOR=FFFFFF TEXT=000000>

<CENTER>

<IMG WIDTH=346 HEIGHT=34 SRC=”previewertitle.gif”><BR>

<IMG WIDTH=108 HEIGHT=26 SRC=”../images/previewercredit.gif”>

</CENTER>

<FORM NAME=”previewForm”>

Please select an image from the following image list, then

select the <B>Preview Image</B> button to preview the image.

To preview additional images, just move the preview window

to the side and select another image from the list. You do

not need to close the preview window.<p>

<CENTER>

<select NAME=”imagename”>

<option value=”image1.gif”>Palm Trees

<option value=”image2.gif”>Sunset

</select>

<input type=button value=”Preview Image” onClick=”display_image(this.form)”>

</CENTER>

</FORM><HR>

</BODY></HTML>

Summary

JavaScript creates many new ways to interact with users. Using JavaScript’s event handlers, your pages can now respond to users’ clicks before they move to the next page. You can provide context-sensitive help in the status bar, or open a window when a user simply moves over an area on your page. These types of dynamic user feedback are crucial to expanding the role of the Internet in new and more interactive ways.

Validating form input now allows your server to work smarter instead of harder. Let the user’s client handle the load of verifying that the input is correct, and then it can be sent to your server error-free.

JavaScript allows for sophisticated mathematical applications to run completely on the client side, which again frees up valuable resources on your server and, at the same time, gives your users near instant feedback to their requests.

Using JavaScript, there are many possibilities for the creation of new user interfaces. Opening new windows and creating your own custom interface can greatly increase the value of your site to your users. These features are only the tip of the iceberg when it comes to the potential of JavaScript. Even though a scripting language, JavaScript is full-featured and robust enough for almost any application.

The next chapter covers some advanced issues in using JavaScript, including using JavaScript with frames and using HTTP cookies.


Previous Page toc Index Next Page