Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Schongar P.VBScript unleashed.1997

.pdf
Скачиваний:
46
Добавлен:
23.08.2013
Размер:
1.59 Mб
Скачать

Document.write "<BODY>"

Document.write Date

Document.write "<P>"

Document.write "<FONT FACE='Verdana'>"

Document.write "<H1>VBScript Unleashed</H1>"

Document.write "<B>Learn how to</B><P>"

Document.write "<UL>"

Document.write "<LI>activate your Web pages with VBScript<BR>"

Document.write "<LI>use Layouts and ActiveX Controls<BR>"

Document.write "<LI>optimize your VBScript code<BR>"

Document.write "<LI>customize your pages with cookies<BR>"

Document.write "<LI>develop intranet applications<BR>"

Document.write "<LI>and much, much more"

Document.write "</UL>"

Document.write "</BODY>"

</SCRIPT>

</HTML>

Notice that the code sets the color value of the document's bgColor property as soon as it's loaded and then places all the other elements on the page. The entire document is generated on the fly with the write method. This example shows exactly what makes the document such a flexible object. Of course, outputting the HTML commands that will produce the desired output with the write method takes quite a bit of typing, but you can automate this process with a simple program that reads actual HTML code and creates write statements whose arguments are the lines of the HTML code. You must make sure that the HTML code uses single quotes (see the line that changes the font of the document), which will not interfere with the double quotes surrounding the write method's arguments.

Color Cycling

Another interesting trick is to rapidly cycle the background color through a range of colors right before loading a new page. If the page's background color is red, you can start with a black background color, which swiftly changes from black to red and then remains red for the rest of the session. Unfortunately, this effect can be depicted on a page, so you must open the FadeColor page and see how it behaves as it loads the page. It starts with a black background that gradually shifts to red. The entire effect lasts less than a second, but it's quite impressive. To see the effect again, click on the Refresh button.

The code that produces this effect is surpassingly simple. It cycles the background color through a range of color values from black to red, with a For...Next loop:

<SCRIPT LANGUAGE=VBS>

For i=0 to 255 step 3

colorVal= "#" & Hex(i) & Hex(0) & Hex(0)

Document.bgColor=colorVal

Next

</SCRIPT>

You can change the step to make the effect faster or slower, and you can also change the arguments of the Hex() function to cycle the background color from any initial value to any final value. This code is placed in the <SCRIPT> tag and outside any procedure so that it will be executed as soon as the HTML document starts loading and before any other element appears. If you attempt to cycle the background color after placing the strings or any other element on the page, the entire page will flicker. The smoothest color cycling is achieved with gray tones. For example, you can start from white and move slowly to a mid-gray tone with a loop like this one:

For i=0 to 128 step 2

colorVal= "#" & Hex(i) & Hex(i) & Hex(i)

Document.bgColor=colorVal

Next

A characteristic of gray tones is that all three color components are the same.

A Yearly Calendar

The previous example shows how to send straight HTML code to the current window. It's an interesting technique, but you can achieve the same by supplying the equivalent HTML document. The example in this section demonstrates the flexibility of the document object's write method, namely how to create documents that produced different output on different systems, depending on the user's actions. The Calendar project displays a tabular arrangement of Command buttons with the names of the months, as shown in Figure 6.4. The user can click on a month's name and see the corresponding calendar. (See Figure 6.5.) The monthly calendar is generated on the fly with VBScript code. The actual calendar doesn't react to a mouse click, but once you understand how it was generated, you can enhance the application by making certain days hyperlinks to other files on the server (for example, you can display major events, project deadlines, and so on). You can even add code behind the digits of the days.

Figure 6.4 : The Calendar application starts by displaying the months of the year. To see a month calendar, click the corresponding button.

Figure 6.5 : A monthly calendar, as displayed by the Calendar application. To return to the previous screen, click the Refresh button.

The complete listing of the project is shown here. The HTML lines that display the twelve month names as command buttons are the document's body, and the rest of the code is the script that creates the current month's calendar.

<HTML>

<HEAD>

<TITLE>Yearly Calendar</TITLE>

<SCRIPT LANGUAGE=VBS>

Sub JANUARY_onClick()

DisplayMonth(1)

End Sub

Sub FEBRUARY_onClick()

DisplayMonth(2)

End Sub

Sub MARCH_onClick()

DisplayMonth(3)

End Sub

Sub APRIL_onClick()

DisplayMonth(4)

End Sub

Sub MAY_onClick()

DisplayMonth(5)

End Sub

Sub JUNE_onClick()

DisplayMonth(6)

End Sub

Sub JULY_onClick()

DisplayMonth(7)

End Sub

Sub AUGUST_onClick()

DisplayMonth(8)

End Sub

Sub SEPTEMBER_onClick()

DisplayMonth(9)

End Sub

Sub OCTOBER_onClick()

DisplayMonth(10)

End Sub

Sub NOVEMBER_onClick()

DisplayMonth(11)

End Sub

Sub DECEMBER_onClick()

DisplayMonth(12)

End Sub

Sub DisplayMonth(imonth) dim MonthName(12) MonthName(1)="January" MonthName(2)="February" MonthName(3)="March" MonthName(4)="April" MonthName(5)="May" MonthName(6)="June" MonthName(7)="July" MonthName(8)="August" MonthName(9)="September" MonthName(10)="October" MonthName(11)="November" MonthName(12)="December"

document.clear document.write "<CENTER>"

document.write "<FONT FACE='Verdana' SIZE=5>" document.write MonthName(imonth) & " " & Year(date) document.write "<P>"

document.write "<TABLE CELLPADDING=10 BORDER><TR>"

document.write

"<TD><B>Sun<TD><B>Mon<TD><B>Tue<TD><B>Wed<TD><B>Thu<TD><B>Fri<TD><B>Sat" document.write "<TR>"

firstdate=DateSerial(year(date), imonth, 1) thisdate=firstdate

nextday=1

For cday=1 to 7

If WeekDay(thisdate)>cday Then

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

else

document.write "<TD ALIGN=CENTER><FONT SIZE=3>" & nextday & "</TD>" nextday=nextday+1

thisdate=DateSerial(year(date), imonth, nextday) End If

Next

document.write "<TR>" weekDays=1

while month(thisdate)=imonth

document.write "<TD ALIGN=CENTER><FONT SIZE=3>" & nextday & "</TD>" nextday=nextday+1

weekDays=weekDays+1 If weekDays>7 then

WeekDays=1 document.write "<TR>"

End If

thisdate=DateSerial(year(date), imonth, nextday) wend

document.write "</TABLE>" document.write "</CENTER>" document.close

End Sub </SCRIPT> </HEAD> <BODY>

<FONT FACE="Comic Sans MS"> <CENTER>

<H1>Yearly Calendar</H1>

Click on a month to see a weekly calendar <P>

<FONT FACE="Verdana" SIZE=6>

<TABLE CELLPADDING=10 BORDER>

<TR>

<COLGROUP>

<COL ALIGN=CENTER>

<COL ALIGN=CENTER>

<COL ALIGN=CENTER>

<TD><INPUT TYPE=BUTTON NAME="January" VALUE="JANUARY">

<TD><INPUT TYPE=BUTTON NAME="February" VALUE="FEBRUARY">

<TD><INPUT TYPE=BUTTON NAME="March" VALUE="MARCH">

<TR>

<TD><INPUT TYPE=BUTTON NAME="April" VALUE="APRIL">

<TD><INPUT TYPE=BUTTON NAME="May" VALUE="MAY">

<TD><INPUT TYPE=BUTTON NAME="June" VALUE="JUNE">

<TR>

<TD><INPUT TYPE=BUTTON NAME="July" VALUE="JULY">

<TD><INPUT TYPE=BUTTON NAME="August" VALUE="AUGUST">

<TD><INPUT TYPE=BUTTON NAME="September" VALUE="SEPTEMBER">

<TR>

<TD><INPUT TYPE=BUTTON NAME="October" VALUE="OCTOBER">

<TD><INPUT TYPE=BUTTON NAME="November" VALUE="NOVEMBER">

<TD><INPUT TYPE=BUTTON NAME="December" VALUE="DECEMBER">

</TABLE>

</BODY>

</HTML>

The 12 command buttons that correspond to the months of the year are placed on the page with straight HTML code. Each button's name corresponds to a month's name, and its onClick event handler displays the actual month calendar. The handler for the onClick event of the JANUARY button is

Sub JANUARY_onClick()

DisplayMonth(1)

End Sub

The handlers of the other Click events are similar. They all call the DisplayMonth() subroutine with the proper arguments. The DisplayMonth() subroutine goes through the days of the specified month and prints them under the appropriate day column.

The program first displays the days of the week as headings. The next step is the display of the days of the first week with a For...Next loop. The first week in the month is usually incomplete and the first few cells in the table must remain blank. This loop goes through the seven days in the week until it hits the first day in the month, which happens when the weekday of the first day in the month is the same as the current cell. Until this happens, the program displays empty cells by writing the string <TD></TD> to the document. After the first day in the month is found, the program creates cells where it places the value of the variable nextday, which is increased with every iteration. The string that produces a cell with a number is:

"<TD ALIGN=CENTER><FONT SIZE=3>" & nextday & "</TD>"

This is HTML code, and any references to variables will be replaced with the actual variable value. If the value of the nextday variable is 24, the line that is written to the document is

<TD ALIGN=CENTER><FONT SIZE=3>24</TD>

which is straight HTML.

After the first week of the calendar has been displayed, the program continues with the following ones. These weeks are complete, except for the last one, of course.

The remaining days of the month are handled with a While...Wend loop. With each iteration, the nextday variable increases by one day, and the loop keeps going as long as you are in the same month (the condition while month (thisdate)=imonth). This loop makes use of an additional variable, the weekDays variable, which increases by one with each iteration and is reset back to 1 when it reaches 7. At the same time, the program inserts a <TR> tag to the output to start a new row in the table.

The code of the DisplayMonth() is fairly straightforward, and you can use it as a starting point for any application that needs to display a calendar. You can easily turn each day of the month into a hyperlink, pointing to a file on the server. If you maintain a separate document for each day of the month on the server, you can modify the application so that each day is a hyperlink to this date's file. Instead of writing the number of the day to the output, you could write a string that will turn it into a hyperlink. If you use the following string as the write method's argument:

"<A HREF=" & imonth & "-" & nextday & ".htm>" & nextday & "</A>"

the actual string that will be written to the output file is

<A HREF=1-21.htm>21</A>

which is indeed a hyperlink to the file 1-21.htm on the server. This file must reside on the same folder as the Calendar application, or you must prefix the filename with a relative pathname.

The history Object

The history object is an invisible object that provides methods for navigating through the document's history. It provides the functionality of the browser's navigational buttons, with the added benefit that you can access this functionality through programming. The following text explains the history object's methods.

Back n

Moves back in the history list by n steps, as if the user has clicked on the browser's Back button n times. To move to the most recently visited URL, use the statement

window.history.back 1

Forward n

Moves forward in the history list by n steps, as if the user has clicked on the browser's Forward button n times.

Go n

Moves to the nth item in the history list. The statement

window.history.go 1

will take you to the first URL in the list.

The history object also provides a property, the length property. This property represents the number of URLs in the history list. The current implementation of Internet Explorer always returns the number zero as the history list's length.

The HistoryObject Project

The HistoryObject document contains a floating frame and three command buttons, which enable you to control the contents of the floating frame. The first button enables the user to type the URL he or she wants to visit in an Input box; it then sets the frame's URL to the string entered by the user. The example uses a frame to display the various URLs, because if the window were updated using the write method, the new document would replace the original contents, including the command buttons. A frame makes it possible to provide the controls for manipulating the frame's URL via the history object's methods. You could also display the URL in a different window (see the open method of the window object), but this approach requires that the viewer moves back and forth between two windows.

You can enter a few URLs to visit manually. (Just remember to enter a fully qualified URL, including the protocol identifier, such as http://www.mcp.com/sams.) You can also follow the hyperlinks in the first URL, which appear when the project is opened for the first time. Then, you can test the Previous URL and Next URL buttons, which simply call the Back and Forward methods of the frame's history object. The document that produced the page in Figure 6.7 appears in the following code:

<HTML>

<HEAD>

<SCRIPT LANGUAGE=VBS>

Sub GoURL_onClick()

newURL=InputBox("Enter the URL of the location you want to visit")

Window.frames(0).location.href=newURL

End Sub

Sub NextURL_onClick()

window.frames(0).history.forward 0

End Sub

Sub PreviousURL_onClick()

window.frames(0).history.back 0

End Sub

</SCRIPT>

<CENTER>

<TABLE WIDTH=500>

<TR>

<TD ALIGN=CENTER><INPUT TYPE=BUTTON VALUE="Get me to this URL" NAME="GoURL" >

<TD ALIGN=CENTER><INPUT TYPE=BUTTON VALUE=" Previous URL "

NAME="PreviousURL" >

<TD ALIGN=CENTER><INPUT TYPE=BUTTON VALUE=" Next URL " NAME="NextURL" >

</TABLE>

<P>

<IFRAME WIDTH=500 HEIGHT=400 NAME="MyFrame" SRC="http://www.microsoft.com">

</CENTER>

</HTML>

To display the URL entered in the Input box, the program assigns the string returned by the InputBox() function to the href property of the frame's location object. The other two buttons invoke the back and forward methods of the frame's history object.

When the page is first loaded, it connects to the Microsoft Web site, which appears in the frame. You can follow the hyperlinks of this document to switch to any other page within the same Web site or to visit another site. Some hyperlinks, however, cause the destination page to be displayed on the parent page (with the <A> tag's TARGET attribute), in effect removing your page from the browser's window. If this happens, the page with the command buttons will be replaced on the browser's window, and you must click on the browser's Back button to return to the LocationObject page, or click the Refresh button to reload the original page.

The navigator Object

This object, also invisible, returns information about the browser. You can access this information through the properties exposed by the navigator object, which are all read-only. An explanation of these properties appears in the following section:

appCodeName

Returns the code name of the application. Internet Explorer 3.0 returns Mozilla.

appName

Returns the name of the application. Internet Explorer 3.0 returns Microsoft Internet Explorer.

appVersion

Returns the version of the application. Internet Explorer 3.0 returns 2.0 (compatible; MSIE 3.0A; Windows 95).

userAgent

Returns the user agent of the application. Internet Explorer returns 2.0 (compatible; MSIE 3.0A; Windows 95).

The most practical use of the navigator object involves detecting whether the client is using Internet Explorer or another browser. Say that you have prepared an HTML page that can be viewed with any browser, and a more advanced version of the same page that makes use of floating frames and style sheets. These two features are currently supported by only Internet Explorer 3.0. You can easily detect which browser the client has running and display the appropriate page.

The BrowserInfo project you explore in the next section demonstrates the use of the navigator object's properties. The next example, NavigatorObject, shows you how to detect whether the browser used on the client is Internet Explorer and adjust the contents of the page accordingly.

The BrowserInfo Project

The BrowserInfo project demonstrates the properties of the navigator object. The BrowserInfo page, which you can find in this chapter's folder on the CD, contains a floating frame. This frame displays the Sams Web site and four command buttons with the four properties of the navigator object. Click the corresponding command button, and you see the values of the navigator object's properties, as reported by Internet Explorer. You should also open this project with other browsers to examine its behavior.

The code of the BrowserInfo page appears in the following text:

<HTML>

<HEAD>

<SCRIPT LANGUAGE=VBS>

Sub BrowserName_onClick()

MsgBox window.navigator.AppName

End Sub

Sub BrowserCodeName_onClick()

MsgBox window.navigator.AppCodeName

End Sub

Sub BrowserVersion_onClick()

MsgBox window.navigator.AppVersion

End Sub

Sub BrowserAgent_onClick()

MsgBox window.navigator.UserAgent

End Sub

</SCRIPT>

<CENTER>

<TABLE WIDTH=500>