Chapter 13

Dynamic Web Page Building

by Craig Eddy


CONTENTS

Perhaps the most exciting aspect of the World Wide Web is the amount of interactivity that can be provided. The advent of JavaScript and VBScript has furthered the cause of interactive Web sites. Using VBScript, it is possible to create a dynamic Web page without having to resort to server-side programming.

You create a dynamic Web page by taking a static HTML file and embedding VBScript code within it. The VBScript code provides the dynamic aspect by changing what is displayed on the page as well as how it is displayed. Your pages can be dynamic on a continuous basis (changing over time while the page is being viewed), or they can be dynamic at load time (the page that loads changes when it's loaded, but then is static). Once you have a grasp of what objects and functions are available to your scripts, you easily can design scripts that display dynamic information and change the page's presentation.

This chapter covers the basics of creating a dynamic Web page using VBScript. The first section covers the Internet Explorer's Document object, which contains properties and methods relative to the currently loaded Web page. Then the ActiveX Timer control is discussed. You can use this control to display messages, change the status bar text, or change the look of the page on a continuous basis. The chapter concludes with several sections describing specific ways to use VBScript to make your Web pages dynamic.

Using the Internet Explorer Document Object

The Internet Explorer exposes an entire hierarchy of objects to the scripts it is hosting. This hierarchy, or object model, provides your scripts with access to information about everything from the browser window itself (via the Window object) all the way down to an individual HTML form element (via the Forms collection of the Document object).

Because the topic of this chapter is dynamic Web pages, the Document object is the only object discussed here. This is not meant to imply that the other objects in the model aren't accessible or useful to VBScript, but they aren't necessary to create dynamic pages.

The Document object provides access to the HTML source code that exists on the page. Using the Document object, you can both read and write the HTML for the page. You also can control the document's color elements as well as access and modify the value of any HTML form elements contained within the document.

This section discusses the Document object's properties, collections, and methods in enough detail to use them in the examples presented throughout the rest of the chapter. You can find documentation on the Internet Explorer object model at http://www.microsoft.com/intdev/sdk/docs/scriptom/.

Properties and Collections

The Document object's properties and collections provide access to various HTML attributes for the Internet Explorer's currently loaded page. These attributes include the various color elements, the available HTML forms, a collection of links, a collection of anchors, and access to the client-side cookie file for the current page. Cookies are a means of storing information on the client's machine that can be retrieved later by the Web server when the client requests the page again.

The Color Properties

The current version of the HTML specification enables the Web page designer to specify the colors to be used to render certain elements on the page. You can control the text color used for links, the default foreground color (for text that is not a link), and the document's background color. Table 13.1 lists these properties.

Table 13.1. The Document object's color properties.

PropertySpecifies
alinkColorColor for an active link
bgColorColor for the page background
fgColorColor for text and other foreground items
linkColorColor for a link
vlinkColorColor for a visited link

NOTE
When the user holds down the mouse button over a link, that link is considered active. The link's color then changes to the color specified by the alinkColor property. Internet Explorer does not have this feature, however, so the link's color always remains the color specified by linkColor (or the default link color if linkColor is not specified).

The link color properties can be set only while the page is loading. The bgColor and fgColor properties can be set when the page loads as well as after the page has loaded. This capability enables you to create an on-the-fly color scheme for users. If they don't like the default colors you've chosen for the page, they can click a button, for example, to set a new color scheme. Or you can provide a drop-down list of available color schemes from which the user can choose. These are discussed in the section "Changing the Document's Colors," later in this chapter.

The Location Property

This property returns a string representation of the document's URL.

WARNING
The Microsoft Web site's Internet Explorer scripting object model documentation defines this property as a reference to a Location object. Internet Explorer, however, does not recognize this property as such, but simply as a string representing the URL for the document.

The LastModified Property

This property returns the date and time the document was last modified.

The Title Property

The document's title is returned by this property. This is the string specified between the HTML document's <TITLE>...</TITLE> tags.

The Referrer Property

This property provides the URL for the page the user was on when he clicked a link that brought him to the current page. If the user is on a page with URL http://www.myserver.com/page1.htm, for example, and he clicks a link that takes him to http://www.myserver.com/page2.htm, the Referrer property on the second page evaluates to http://www.myserver.com/page1.htm.

If the user opened the page by clicking a link in another page, the Referrer property returns NULL.

The Cookie Property

The term cookie refers to a piece of data stored on the user's machine. The data is relative to a certain Web page and is sent to Web servers that house the page the cookie belongs to when the page is requested by the browser. Cookies enable Web site designers to store user preferences and other information on the client's machine instead of on the Web server somewhere. You can store a cookie for the date and time the user last viewed a particular page, for example. When the user returns to the page, your VBScript code can access this cookie information and provide a message like Welcome back, it's been 10 days since your last visit.

Cookies are defined as a name and value associated with that name. Reading the Cookie property returns a string of all the names and values for the current page. This string separates each cookie name/value pair with a semicolon. To set a new cookie pair or modify an existing cookie's value, simply assign the pair to the Cookie property, as shown in this example:


Document.Cookie = strCookieName & "=" & strCookieValue

Here, strCookieName is a variable containing the name for the cookie and strCookieValue contains the value for the cookie. These variables can be replaced with hard-coded strings, of course.

Cookies also have an expires attribute that specifies the date after which the cookie no longer is valid. If an expires attribute is not specified, the cookie should expire at the end of the current browser session (that is, when the user exits the browser application). The expires attribute should be appended to the string assigned to the Cookie property. To set a cookie that expires on December 31, 1999 at midnight Greenwich mean time, for example, use this code:


Document.Cookie = strCookieName & "=" & strCookieValue & ";expires=31-Dec-99 GMT"

To remove a cookie from the client's machine, set its value to NULL and give it an expires attribute that matches some date in the past. For example:


Document.Cookie = strCookieName & "=NULL;expires=01-Aug-96"

removes the cookie specified in strCookieName.

The section "Using Cookies to Maintain User Information," later in this chapter, demonstrates in more detail how to access cookies using VBScript code. For a technical discussion of cookies in general, see the Netscape page describing them at http://home.netscape.com/newsref/std/cookie_spec.html.

NOTE
To use cookies, the page must be stored on and served by a Web server. This is due to the fact that cookies are actually a part of the HTTP specification and therefore require an HTTP client/server conversation in order to work. Therefore, cookies will not work when you are saving a page to a local hard drive and loading it using Internet Explorer's file browser.

The anchors Collection

The anchors collection is an array of the anchors contained in the document. An anchor is a named reference to a section of the document. Anchors are defined using the HTML tag <a NAME=anchor-name>...</a> and can be referenced in a link by <a HTEF=page-url#anchor-name>. This URL loads the page specified and transfers the user to the place where the anchor is specified.

The anchors collection has a length property. To determine how many anchors are contained in the document, use document.anchors.length. To reference the string for the first anchor in the document, use document.anchors[0].

The links Collection

The links collection is almost identical to the anchors collection. It also has a length property, and you reference items in the array using document.links[x]. The links array contains all the hyperlinks that take you to another page or to an anchor in the current document.

The forms Collection

The forms collection returns an array of all the HTML forms contained in the document. It also has a length property, and individual form objects are referenced using document.forms[x]. You then can reference an individual element of a form using document.forms[x].input1, for example.

Methods

The document object provides several useful methods that can be used to manipulate the contents of the document and open a new document.

The Write and Writeln Methods

These methods are used to print HTML text to the document. The text is printed at the point where the script is placed. The text is placed directly into the document and therefore must be formatted as HTML text. The difference between the two methods is that the Writeln method also appends a newline character to the end of the text written to the document.

The section "Writing the Current Date and Time to the Page," later in this chapter, gives you several examples of using the Write and Writeln methods. As a quick example, the HTML code in Listing 13.1 produces the Web page shown in Figure 13.1.

Figure 13.1 : The Writeln example's resulting page.


Listing 13.1. Writeln sample code.

<HTML><HEAD>

<TITLE>New Page</TITLE>

</HEAD><BODY>

<SCRIPT LANGUAGE="VBScript">

<!--

window.Document.Writeln "appCodeName: " & window.navigator.appCodeName & "<br>"

window.Document.Writeln "appName: " & window.navigator.appName & "<br>"

window.Document.Writeln "appVersion: " & window.navigator.appVersion & "<br>"

window.Document.Writeln "userAgent: " & window.navigator.UserAgent & "<br>"

window.Document.Writeln "LastModified: " & window.Document.LastModified & "<br>"

window.Document.Writeln "Referrer: " & window.Document.Referrer & "<br>"

window.Document.Writeln "Title: " & window.Document.Title & "<br>"

window.Document.Writeln "Location: " & window.Document.Location & "<br>"

-->

</SCRIPT>



<H1>Document.Writeln Example</H1>



<SCRIPT LANGUAGE="VBScript">

<!--

Document.Writeln "appCodeName: " & window.navigator.appCodeName & "<br>"

-->

</SCRIPT>

</BODY>

</HTML>


The Open, Close, and Clear Methods

The Open, Close, and Clear methods are used to create and write to a completely new document object. The Open method is used to start a new document. It clears the current document and prepares it for writing. The Close method is used after HTML text is written to the document to display all the text written to the document since the Open method was invoked. The text is not displayed until the Close method is used. The Clear method is used to clear the document of any existing data.

As a quick example, the code in Listing 13.2 produces the Web page shown in Figure 13.2. Note that only the text from the window_onLoad event code is shown-not the HTML contained in the <BODY>...</BODY> section of the listing. When the page loads, the <H1> section's text shows up briefly and then is replaced by the text from the onLoad event.

Figure 13.2 : The Open/Close example's resulting page.


Listing 13.2. Using the Open and Close methods.

<HTML><HEAD>

<SCRIPT LANGUAGE="VBScript">

<!--

Sub window_onLoad()

window.document.open "text/html"

window.document.writeln "<H2>"

window.document.writeln "This text is from the window_onLoad event!"

window.document.writeln "</H2>"

window.document.close

end sub

-->

</SCRIPT>

<TITLE>New Page</TITLE>

</HEAD>

<BODY>

<H1>This Doesn't Show Up!!!</H1>

</BODY>

</HTML>


Using the ActiveX Timer Control

Now that you've learned how to manipulate the Document object, it's time to put that knowledge to use. This section describes the ActiveX Timer object and how to use it to create dynamic documents.

You can download the ActiveX Timer control from the Microsoft Web site at http://www.microsoft.com/workshop/activex/gallery/ms/timer/sample.htm. Before you go to the trouble, however, check to see whether you already have a copy on your system. The best way to do so is to run the ActiveX Control Pad and choose the Edit | Insert ActiveX Control menu. The Timer control appears as Timer Object in the Control Type list box.

The Timer control has three properties that are useful within VBScript code: Interval, Enabled, and ID. There is only one event: Timer. The Interval property determines the amount of time, in milliseconds, between calls of the Timer event. The Enabled property enables and disables the control. The ID property serves as the control's name. The Timer event is the event that fires with each passing of the time specified by the Interval property.

You can use the Timer control to create any type of dynamic effect you want. You can use it to randomly change the status bar text, open new documents, navigate to another Web page, and so on. The code in Listing 13.3 shows an example of opening a new document two seconds after the page loads and writing some text to it. Figure 13.3 shows the resulting page.

Figure 13.3 : The resulting page from the ActiveX Timer control example.


Listing 13.3. Using the ActiveX Timer control.

<HTML><HEAD>

<TITLE>New Page</TITLE>

</HEAD>

<BODY>

<H1>This Will Disappear Soon!!!</H1>

    <SCRIPT LANGUAGE="VBScript">

<!--

Sub IeTimer1_Timer()

window.document.open "text/html"

window.document.writeln "<H2>"

window.document.writeln "This text is from the "

window.document.writeln "Timer event!"

window.document.writeln "</H2>"

window.document.close

end sub

-->

</SCRIPT>

<OBJECT ID="IeTimer1" WIDTH=39 HEIGHT=39

 CLASSID="CLSID:59CCB4A0-727D-11CF-AC36-00AA00A47DD2">

    <PARAM NAME="_ExtentX" VALUE="1032">

    <PARAM NAME="_ExtentY" VALUE="1032">

    <PARAM NAME="Interval" VALUE="2000">

</OBJECT>

</BODY>

</HTML>


The page initially loads and displays the message This Will Disappear Soon!!!. After two seconds, the value of the Interval property, the IeTimer1_Timer event, fires. This event uses the Document object's Open, Writeln, and Close methods to create a new document and print the text This text is from the Timer event! Note that on the new document there is no Timer control, so the code executes only once. Because you're writing HTML to the document, however, you could have placed the Timer object and its associated code into the new document. This could be used to create a slide show but, due to the cascading nature of the code you'd have to enter into the script, it would be hard to maintain.

Writing the Current Date and Time to the Page

Perhaps one of the most useful features for creating dynamic Web pages is the capability to write the current date and time to the page. This is accomplished using the Document object's Writeln property and VBScript's various date and time functions.

The concept is simple: As the page loads, an embedded script uses the Document.writeln method to print a string containing the current date and time at the point in the HTML file where the script appears. Using the various date/time functions, you can format the string in any manner you want. The example presented in this section formats the date as Friday, August 9, 1996 and leaves the time in the format returned by the VBScript Time function.

Although the example presented here is not all that useful by itself, when combined with a "real" Web page, it provides a nice touch for your site. Figure 13.4 shows the output from the script. The code is presented in Listing 13.4.

Figure 13.4 : The current date/time written to the page.


Listing 13.4. The code for the date/time example.

<HTML><HEAD>

<TITLE>Current Date & Time</TITLE>

</HEAD><BODY>

<center>

<SCRIPT LANGUAGE="VBScript">

<!--

Dim DayOfWeek

Dim MonthText

Dim strTemp



select case Weekday(Date)

  case 1

      DayOfWeek = "Sunday"

case 2

      DayOfWeek = "Monday"

case 3

     DayOfWeek = "Tuesday"

Case 4

     DayOfWeek = "Wednesday"

case 5

     DayOfWeek = "Thursday"

case 6

     DayOfWeek = "Friday"

case 7

     DayOfWeek = "Saturday"

end select



Select Case Month(Date)

case 1

      MonthText = "January"

case 2

      MonthText = "February"

case 3

      MonthText = "March"

case 4

      MonthText = "April"

case 5

      MonthText = "May"

case 6

      MonthText = "June"

case 7

      MonthText = "July"

case 8

      MonthText = "August"

case 9

      MonthText = "September"

case 10

      MonthText = "October"

case 11

      MonthText = "November"

case 12

      MonthText = "December"

end select

strTemp = DayOfWeek & ", " & MonthText & " "

strTemp = strTemp & Day(Date) & ", " & Year(Date) & "<br>"

document.writeln strTemp

document.writeln Time

-->

</SCRIPT>

</center>

</BODY></HTML>


The script code shown in Listing 13.4 is embedded within the HTML file's <BODY> section. This section contains the HTML that will be visible in the document window of the Web browser. The <CENTER> tag is used to center the date and time strings within the document window. The code begins by declaring three local variables: DayOfWeek, MonthText, and strTemp. These are used to construct the date string that will be displayed. The script then uses a Select Case construct to place the name of the current day of the week in DayOfWeek. The Weekday() function returns an integer corresponding to the day of the week for the date passed to it as its only parameter. In this case, the Date function is used; it returns the current date.

After the DayOfWeek value is assigned, another Select Case is used to assign a value to MonthText. This time, the Month() function is called in order to retrieve the number of the current month. Finally, the value for strTemp is assigned by combining the previous variables with the Day() and Year() functions. The value of strTemp is written to the document window using the writeln method. Then, the current time (returned by the Time function) also is written to the document.

Notice that this produces a static display. After the page is loaded, the date and time are not updated. If you want to create an updating date/time display, simply add ActiveX Label and Timer controls. Set the timer's Interval property to be the time between updates of the display and use 1000 for one second between updates. Then, in the Timer event, simply assign the strings created in the preceding example to the label's Caption property. Listing 13.5 provides an example of how this can be accomplished.


Listing 13.5. The code for the date/time using a label example.

<HTML>

<HEAD> <SCRIPT LANGUAGE="VBScript">

<!--

Sub window_onLoad()

Call IeTimer1_Timer

end sub

-->

</SCRIPT>

<TITLE>Updating Clock</TITLE>

</HEAD>

<BODY>

<CENTER>

<OBJECT ID="lblDate" WIDTH=259 HEIGHT=27

 CLASSID="CLSID:99B42120-6EC7-11CF-A6C7-00AA00A47DD2">

    <PARAM NAME="_ExtentX" VALUE="6853">

    <PARAM NAME="_ExtentY" VALUE="714">

    <PARAM NAME="Caption" VALUE="">

    <PARAM NAME="Angle" VALUE="0">

    <PARAM NAME="Alignment" VALUE="1">

    <PARAM NAME="Mode" VALUE="1">

    <PARAM NAME="FillStyle" VALUE="0">

    <PARAM NAME="FillStyle" VALUE="0">

    <PARAM NAME="ForeColor" VALUE="#000000">

    <PARAM NAME="BackColor" VALUE="#C0C0C0">

    <PARAM NAME="FontName" VALUE="Arial">

    <PARAM NAME="FontSize" VALUE="12">

    <PARAM NAME="FontItalic" VALUE="0">

    <PARAM NAME="FontBold" VALUE="0">

    <PARAM NAME="FontUnderline" VALUE="0">

    <PARAM NAME="FontStrikeout" VALUE="0">

    <PARAM NAME="TopPoints" VALUE="0">

    <PARAM NAME="BotPoints" VALUE="0">

</OBJECT>

<br>

<OBJECT ID="lblTime" WIDTH=259 HEIGHT=39

 CLASSID="CLSID:99B42120-6EC7-11CF-A6C7-00AA00A47DD2">

    <PARAM NAME="_ExtentX" VALUE="6853">

    <PARAM NAME="_ExtentY" VALUE="1032">

    <PARAM NAME="Caption" VALUE="">

    <PARAM NAME="Angle" VALUE="1">

    <PARAM NAME="Alignment" VALUE="1">

    <PARAM NAME="Mode" VALUE="1">

    <PARAM NAME="FillStyle" VALUE="0">

    <PARAM NAME="FillStyle" VALUE="0">

    <PARAM NAME="ForeColor" VALUE="#000000">

    <PARAM NAME="BackColor" VALUE="#C0C0C0">

    <PARAM NAME="FontName" VALUE="Arial">

    <PARAM NAME="FontSize" VALUE="12">

    <PARAM NAME="FontItalic" VALUE="0">

    <PARAM NAME="FontBold" VALUE="0">

    <PARAM NAME="FontUnderline" VALUE="0">

    <PARAM NAME="FontStrikeout" VALUE="0">

    <PARAM NAME="TopPoints" VALUE="0">

    <PARAM NAME="BotPoints" VALUE="0">

</OBJECT></CENTER>

<SCRIPT LANGUAGE="VBScript">

<!--

Sub IeTimer1_Timer()

Dim DayOfWeek

Dim MonthText

Dim strTemp



select case Weekday(Date)

  case 1

      DayOfWeek = "Sunday"

case 2

      DayOfWeek = "Monday"

case 3

     DayOfWeek = "Tuesday"

case 4

     DayOfWeek = "Wednesday"

case 5

     DayOfWeek = "Thursday"

case 6

     DayOfWeek = "Friday"

case 7

     DayOfWeek = "Saturday"

end select



Select Case Month(Date)

case 1

      MonthText = "January"

case 2

      MonthText = "February"

case 3

      MonthText = "March"

case 4

      MonthText = "April"

case 5

      MonthText = "May"

case 6

      MonthText = "June"

case 7

      MonthText = "July"

case 8

      MonthText = "August"

case 9

      MonthText = "September"

case 10

      MonthText = "October"

case 11

      MonthText = "November"

case 12

      MonthText = "December"

end select

strTemp = DayOfWeek & ", " & MonthText & " "

strTemp = strTemp & Day(Date) & ", " & Year(Date)

lblDate.Caption = strTemp

lblTime.Caption = Time

end sub

-->

</SCRIPT>

    <OBJECT ID="IeTimer1" WIDTH=39 HEIGHT=39

     CLASSID="CLSID:59CCB4A0-727D-11CF-AC36-00AA00A47DD2">

        <PARAM NAME="_ExtentX" VALUE="1005">

        <PARAM NAME="_ExtentY" VALUE="1005">

        <PARAM NAME="Interval" VALUE="1000">

    </OBJECT>

</BODY>

</HTML>


Creating a Random Frame Using Client-Side Refresh

Another method of creating dynamic Web pages is to use client-side refresh to periodically reload a Web page. By combining this HTML feature with VBScript code, you can produce a wonderfully dynamic page. This section describes how to use a Web page with two frames to produce a random famous quotation display. Figure 13.5 shows the resulting Web page.

Figure 13.5 : The Random Famous Quotes display page.

The main HTML file defines a frameset with two frames. Listing 13.6 contains the code for the file. The frameset refers to two frames: PAGE8.htm and PAGE7.htm.


Listing 13.6. HTML for the main page.

<HTML><HEAD><TITLE>Random Famous Quotes</TITLE></HEAD>

<BODY>

<Center><FRAMESET ROWS="15%, *" SCROLLING=NO>

<FRAME SRC="PAGE8.htm" SCROLLING=NO>

<FRAME SRC="PAGE7.htm"></FRAMESET></CENTER>

</BODY></HTML>


The top frame is static. It simply displays a heading. Listing 13.7 contains the code for this page. This file should be saved as PAGE8.htm in the same directory as the main page.


Listing 13.7. HTML for the top frame.

<HTML>

<BODY><P>

<CENTER><H2>Random Famous Quotes</H2></CENTER>

</BODY></HTML>


The bottom frame is the dynamic one. Listing 13.8 contains the code for this page. This file should be saved as PAGE7.htm in the same directory as the main page.


Listing 13.8. HTML for the dynamic frame.

<HTML><HEAD><META HTTP-EQUIV="Refresh" CONTENT="10">

</HEAD>

<BODY>

<script language="vbscript">

<!--

On Error Resume Next

DIM phrase(5)

lowerbound=0



phrase(0) = "When you have a choice and don't make it,"

phrase(0) = phrase(0) & "<br>that is, in itself, a choice.<br>"

phrase(0) = phrase(0) & "-- William James"



phrase(1) = "If you tell the truth, you don't have to remember "

phrase(1) = phrase(1) & "what you said.<br>"

phrase(1) = phrase(1) & "-- Mark Twain"



phrase(2) = "None of my inventions came by accident.<br>"

phrase(2) = phrase(2) & "They came by work.<br>-- Thomas Edison"

phrase(3) = "It is wonderful how much can be done<br>"

phrase(3) = phrase(3) & "if we are always doing.<br>-- Thomas Jefferson"

phrase(4) = "One man with courage makes a majority.<br>"

phrase(4) = phrase(4) & "-- Andrew Jackson"



upperbound=4

Randomize()

pick = Int((upperbound - lowerbound + 1) * Rnd + lowerbound)



document.write "<CENTER><TD BGCOLOR=#EEEEEE ALIGN=CENTER><font size=3>"

document.write phrase(pick)

document.write "</font></TD></CENTER>"

-->

</script>

</BODY></HTML>


The HTML tag <META HTTP-EQUIV="Refresh" CONTENT="10"> instructs the browser to reload the current document every 10 seconds. This is a browser feature and is supported by Internet Explorer.

Because the script is embedded into the <BODY> section, it executes when the page loads. The script first sets up an array of available quotations. Then the Randomize() and Rnd functions are used to generate a random number that serves as the index into the array of quotations. Finally, the document.write method is used to output the quotation and add some formatting.

Changing the Document's Colors

In addition to writing text to the HTML document, you can use VBScript to change the foreground and background colors on-the-fly. You also can change the color used to display links, but only when the page first loads. This section describes how to set the document colors within VBScript.

The example created in this section enables you to choose foreground and background colors from a drop-down listbox. You can choose from several color names in the listbox. After you make a selection, the appropriate color property (foreground or background) is set. The page created appears in Figure 13.6.

Figure 13.6 : The Color Picker Web page.

This page uses the Microsoft Forms 2.0 ComboBox ActiveX control as the drop-down listbox. Using the Microsoft ActiveX Control Pad currently is the easiest way to properly embed ActiveX controls into an HTML file. (The Control Pad is discussed in Chapter 8, "The ActiveX Control Pad.")

Listing 13.9 shows the code for the HTML file.


Listing 13.9. HTML for the Color Picker Web page.

<HTML><HEAD>

<SCRIPT LANGUAGE="VBScript">

<!--

Sub window_onLoad()

cboBGColor.AddItem "Black"

cboBGColor.AddItem "Red"

cboBGColor.AddItem "Green"

cboBGColor.AddItem "Blue"

cboBGColor.AddItem "White"

cboBGColor.ListIndex = 0



cboFGColor.AddItem "Black"

cboFGColor.AddItem "Red"

cboFGColor.AddItem "Green"

cboFGColor.AddItem "Blue"

cboFGColor.AddItem "White"

cboFGColor.ListIndex = 3



end sub

--

</SCRIPT>

<SCRIPT LANGUAGE="VBScript">

<!--

function GetColor(pstrColor)

select case pstrColor

case "Red"

   GetColor = "#FF0000"

Case "Green"

   GetColor = "#00FF00"

case "Black"

   GetColor = "#000000"

case "Blue"

   GetColor = "#0000FF"

case "White"

   GetColor = "#FFFFFF"

end select



end function

-->

</SCRIPT>

<TITLE>Color Picker</TITLE></HEAD>

<BODY>

<SCRIPT LANGUAGE="VBScript">

<!--

Sub cboBGColor_Click()

   window.document.bgColor = GetColor(cboBGColor.Text)



end sub

-->

</SCRIPT>



Background Color:

<OBJECT ID="cboBGColor" WIDTH=93 HEIGHT=24

     CLASSID="CLSID:8BD21D30-EC42-11CE-9E0D-00AA006002f3">

        <PARAM NAME="VariousPropertyBits" VALUE="75499547">

        <PARAM NAME="DisplayStyle" VALUE="7">

        <PARAM NAME="Size" VALUE="2455;635">

        <PARAM NAME="MatchEntry" VALUE="1">

        <PARAM NAME="ShowDropButtonWhen" VALUE="2">

        <PARAM NAME="FontCharSet" VALUE="0">

        <PARAM NAME="FontPitchAndFamily" VALUE="2">

        <PARAM NAME="FontWeight" VALUE="0">

</OBJECT>

<br>Foreground Color:

<SCRIPT LANGUAGE="VBScript">

<!--

Sub cboFGColor_Click()

  window.document.fgColor = GetColor(cboFGColor.Text)

end sub

-->

</SCRIPT>



<OBJECT ID="cboFGColor" WIDTH=93 HEIGHT=24

     CLASSID="CLSID:8BD21D30-EC42-11CE-9E0D-00AA006002f3">

        <PARAM NAME="VariousPropertyBits" VALUE="75499547">

        <PARAM NAME="DisplayStyle" VALUE="7">

        <PARAM NAME="Size" VALUE="2455;635">

        <PARAM NAME="MatchEntry" VALUE="1">

        <PARAM NAME="ShowDropButtonWhen" VALUE="2">

        <PARAM NAME="FontCharSet" VALUE="0">

        <PARAM NAME="FontPitchAndFamily" VALUE="2">

        <PARAM NAME="FontWeight" VALUE="0">

</OBJECT>

</BODY></HTML>


The script code begins execution with the window_onLoad event. This event is fired whenever the page is loaded. The code in this event adds the color names to the drop-down listboxes and sets their ListIndex properties. Doing so fires the respective Click events for the drop-down listboxes, setting the default colors to a black background with a blue foreground.

Next, a function named GetColor() is defined. This function takes a string parameter, pstrColor, and uses a Select Case to return the value for the chosen color. This function is called from the drop-down listboxes' Click event to determine the proper value to assign to the appropriate color property.

After this function, the <TITLE> tag defines the page's title and then the <BODY> portion of the HTML file starts. The first element after the <BODY> tag is another section of script code. This code is for the cboBGcolor_Click event. The code in this event sets the document object's bgColor property to the value returned by GetColor(cboBGColor.Text).

Next, some text is placed on the document to serve as a label for the background color drop-down listbox. Then the <OBJECT> element for the drop-down listbox is inserted. Note that most of the property information for this control is stored in the <PARAM NAME="VariousPropertyBits" VALUE="75499547"> element. This is obviously an encoded number. I used the ActiveX Control Pad to insert and edit this control. The assignment of this property was made by the Control Pad's Control Property feature, hiding the complexity from the Web page designer. In the Control Pad's Property window, I changed the Style property to 2 - DropDownList. This was the only property I modified from the default setting.

Next, the code for the foreground color drop-down listbox is defined. This is essentially identical to the cboBGColor_Click event except that the document object's fgColor property is used. There is then a label for the foreground color drop-down listbox and, finally, the <OBJECT> element for the drop-down listbox. This, except for the ID property (which is set to cboFGColor), is identical to the definition of the background color drop-down listbox.

After the HTML code is entered and saved, load the page into Internet Explorer. The page should load with a black background and a blue foreground. If it doesn't, first check the window_onLoad event to make sure that the proper strings are being used in the AddItem methods and the ListIndex property is being set correctly. Then check the Click event code for the drop-down listboxes and, finally, the GetColor() function. After the page loads properly, try changing the settings in the drop-down listbox. The appropriate color properties should change accordingly.

Using Cookies to Maintain User Information

Another extremely useful method for creating dynamic Web pages using VBScript is the use of cookies. A cookie is a set of information stored on the user's machine that is associated with a particular Web site. The HTTP protocol, which is the transport protocol for the World Wide Web, provides for the setting and retrieving of these cookie files. You can access this information in your VBScript code using the document.cookie property first discussed in the section "The Internet Explorer Document Object," earlier in this chapter.

NOTE
Pages that use cookies must be stored on and retrieved using a Web server. This is because cookies are tied closely to the HTTP protocol. The example presented in this chapter will not function if the file is not saved on a Web server. If you attempt to save a cookie when not on a Web server page, you receive the runtime error number 438, object doesn't support this property or method.

The cookie property is set and retrieved as a string. It can be accessed at any time using your script code. A good use for cookies is the storage of user information relative to your Web page. If you have an order-entry page, for example, you might want to store the user's name and address so that when he returns to the page he won't have to enter it again. The script code reads the cookie property, parses out the name and address variables from it, and places the resulting information in the order-entry form's input boxes. You'll see a full-blown example of doing this in Chapter 25, "Order Entry."

Because the cookie stores multiple pieces of information within a single string, it is necessary to parse the string to retrieve the variable in which you are interested. The string is returned in the cookie property as a semicolon delimited string. Each portion of the string contains the variable name, an equal sign, and the variable's value. For example, First=Craig;Last=Eddy defines a cookie with two variables, First and Last, with values Craig and Eddy, respectively.

To parse the cookie string, I borrowed a function named ReadVariable() from Microsoft's Cookie Demo page (which you can find at http://www.microsoft.com/vbscript/us/vbssamp/cookies/extcookie.htm). This function takes as its only parameter the name of the variable to be retrieved from the cookie string. It returns the value of the variable or the string NOT_FOUND if the variable isn't found within the cookie string.

The simple example in this section stores the user's name and e-mail address in the cookie. It does so by providing Microsoft Forms 2.0 text boxes for the user input. After the user clicks the Save button, the information entered is stored in the cookie. Later, when the page is loaded again, the cookie information is read and if the name and e-mail variables are found, the text boxes are set to the values in the cookies.

Figure 13.7 shows the empty Web page as viewed with Internet Explorer. Listing 13.10 shows the HTML and VBScript code.

Figure 13.7 : The cookie example Web page.


Listing 13.10. The HTML for cookie example.

<HTML><HEAD>

<SCRIPT LANGUAGE="VBScript">

<!--



dim  NOT_FOUND

NOT_FOUND = "NOT_FOUND"



Sub window_onLoad()

Dim lstrTemp, lstrVarName

lstrVarName = "Name"

lstrTemp = ReadVariable(lstrVarName)

if lstrTemp <> NOT_FOUND then txtName.Text = "" & lstrTemp

lstrTemp = ReadVariable("EMail")

if lstrTemp <> NOT_FOUND then txtEMail = cstr(lstrTemp)

end sub

Function ReadVariable(strVariableName)

'these five variables are used in the string manipulation

'code that finds the variable in the cookie.

Dim intLocation

Dim intNameLength



Dim intValueLength

Dim intNextSemicolon

Dim strTemp



'calculate length and location of variable name

intNameLength = Len(strVariableName)

intLocation = Instr(Document.Cookie, strVariableName)



'check for existence of variable name

If intLocation = 0 Then

    'variable not found, so it can't be read

    ReadVariable = NOT_FOUND

Else

    'get a smaller substring to work with

    strTemp = Right(Document.Cookie, Len(Document.Cookie) - intLocation + 1)



    'check to make sure we found the full string, not just a substring

    If Mid(strTemp, intNameLength + 1, 1) <> "=" Then

        'oops, only found substring, not good enough

        ReadVariable = NOT_FOUND

        'note that this will incorrectly give a not found result if and only if

        'a search for a variable whose name is a substring of a preceding

        'variable is undertaken.  For example, this will fail:

        '

        'search for: MyVar

        'cookie contains: MyVariable=2;MyVar=1

    Else

        'found full string

        intNextSemicolon = Instr(strTemp, ";")



        'if not found, then we need the last element of the cookie

        If intNextSemicolon = 0 Then intNextSemicolon = Len(strTemp) + 1



        'check for empty variable (Var1=;)

        If intNextSemicolon = (intNameLength + 2) Then

            'variable is empty

            ReadVariable = ""

        Else

            'calculate value normally

            intValueLength = intNextSemicolon - intNameLength - 2

            ReadVariable = Mid(strTemp, intNameLength + 2, intValueLength)

        End If

    End If

End If

end function



-->

</SCRIPT>

<TITLE>User Information</TITLE>

</HEAD><BODY><pre>

Name:  <br> <OBJECT ID="txtName" WIDTH=187 HEIGHT=24

 CLASSID="CLSID:8BD21D10-EC42-11CE-9E0D-00AA006002f3">

    <PARAM NAME="VariousPropertyBits" VALUE="746604571">

    <PARAM NAME="Size" VALUE="4948;635">

    <PARAM NAME="FontCharSet" VALUE="0">

    <PARAM NAME="FontPitchAndFamily" VALUE="2">

    <PARAM NAME="FontWeight" VALUE="0">

</OBJECT>

E-Mail: <br> <OBJECT ID="txtEMail" WIDTH=187 HEIGHT=24

 CLASSID="CLSID:8BD21D10-EC42-11CE-9E0D-00AA006002f3">

    <PARAM NAME="VariousPropertyBits" VALUE="746604571">

    <PARAM NAME="Size" VALUE="4948;635">

    <PARAM NAME="FontCharSet" VALUE="0">

    <PARAM NAME="FontPitchAndFamily" VALUE="2">

    <PARAM NAME="FontWeight" VALUE="0">

</OBJECT>

<SCRIPT LANGUAGE="VBScript">

<!--

Sub cmdSave_Click()

on error resume next

document.Cookie = "Name" & "=" & txtName

if err.number = 438 then

    msgbox "Error saving cookie: page is not located on a Web server!"

    err.clear

    exit sub

elseif err > 0 then

    msgbox "Error saving cookie: " & err.description

    err.clear

    exit sub

end if

document.Cookie = "EMail" & "=" & txtEMail

if err > 0 then

    msgbox "Error saving cookie: " & err.description

    err.clear

    exit sub

end if

MsgBox "Information saved!"

end sub

-->

</SCRIPT>

    <OBJECT ID="cmdSave" WIDTH=96 HEIGHT=32

     CLASSID="CLSID:D7053240-CE69-11CD-A777-00DD01143C57">

        <PARAM NAME="Caption" VALUE="Save">

        <PARAM NAME="Size" VALUE="2540;846">

        <PARAM NAME="FontCharSet" VALUE="0">

        <PARAM NAME="FontPitchAndFamily" VALUE="2">

        <PARAM NAME="ParagraphAlign" VALUE="3">

        <PARAM NAME="FontWeight" VALUE="0">

    </OBJECT>

</PRE></BODY></HTML>


In the window_onLoad event, the cookie information is read from the document.cookie property using the ReadVariable() function. If the cookie information (name and e-mail) is found, the data is placed in the appropriate text boxes.

The ReadVariable() parses the cookie property, searching for the variable name specified as the strVariableName parameter. It does this by using the Instr() function to locate the starting position of the string specified in strVariableName. If the string is not found, the constant value NOT_FOUND is returned. If the string is found, the ReadVariable() function then checks to make sure the variable name is not a substring of another variable name. If it passes this test, the value is parsed from the string by taking all the characters between the = and the next semicolon. This string is returned as the function's value.

Finally, the cmdSave_Click event code is responsible for saving the cookie information into the cookie property. It does so by assigning the string variable_name=value to the cookie property. Some error handling is in place to provide the user with any feedback that results from this operation. There are limits to how many cookies can be defined for a site and overstepping these limits would produce an error condition.

Review

This chapter provided you with loads of information useful in creating dynamic Web pages by using VBScript. The examples, although not full-blown applications by themselves, provide the framework for further enhancements. The remainder of this book covers special subjects such as animation and controlling Microsoft Office documents with VBScript code. The final part of the book builds on this part by presenting several real-world examples built using VBScript.