All Categories :
ActiveX
Chapter 2
Managing HTML Content:
VBScript,
ActiveX Control Pad,
and Style Sheets
CONTENTS
Microsoft's Visual Basic (VB) has become a widely used programming
language because its ease of use allows developers to quickly
create practical applications. With Visual Basic for Applications
(VBA), which is a subset of VB, programmers can write attractive
front-ends for various Windows programs. For example, an Excel
spreadsheet that uses clumsy menus and in-line action buttons
can be revamped using VBA to have an improved, more professional
appearance. Scroll bars, list boxes, check boxes, and other controls
can be added to accept and validate user input.
And now the Visual Basic Scripting Edition, VBScript for short,
lets developers add scripting capabilities to HTML pages. In this
chapter we'll discuss Visual Basic syntax, variable types, and
other necessary basic information. Then we'll present and discuss
some working VBS applications. Also covered in this chapter are
two other important Microsoft tools for document creation and
appearance: ActiveX Control Pad; and Cascading Style Sheets (CSS),
Microsoft's implementation of Håkon Lie's innovation in
HTML appearance.
VBScript is a yet lighter-weight version of VB. It gives the Web
developer a powerful capacity to automate many tasks that traditionally
have been done through the Common Gateway Interface (CGI). With
CGI, the developer writes a script on the Web server; the script
is executed only when the client makes a request in the form of
opening a TCP/IP connection to the Web server. Often, the server-side
script is merely processing client data, passing back a lot of
similar data to the client in the event of a subsequent submission.
The significant network overhead in these transmissions could
be minimized if the client machine were acting more like a computer
and less like a dumb terminal.
The CGI method may give the user some degree of interactivity,
but the user perceives the process as slow and unreliable. On
the developer's side, extra provisions must be made not only to
maintain the status of previous client's requests, but also to
allow for broken connections between client and server. Furthermore,
the Web system administrator must do capacity planning to accommodate
server load, as multiple TCP/IP connections fork off numerous
CGI processes. This degrades performance and can exhaust the server
memory. Together, it all adds significant overhead to processing
on the Web, without offering true interactivity.
Just as the ActiveX tools have evolved over time, so has scripting.
The concept of automating programs with scripting or macro languages
is at least as old as the character-based display terminal. Before
Microsoft implemented client-side scripting, Netscape offered
JavaScript-an interesting scripting language having more in common
with its progenitor, LiveScript, than with the full network-programming
language, Java. Microsoft's innovation to the scripting concept
is the method used to implement VBScript: the OLE Scripting Service.
With the OLE Scripting Service, a program such as Internet Explorer
can be extended to include a "scripting engine," which
allows generic scripts to be executed in a surprisingly generic
manner. The host program and the scripting engine itself have
no knowledge of the scripting language. Therefore, if the
host program has the script-engine capability, any scripting language
can be adapted to run within the host program, without further
modification to the host program.
In addition to Internet Explorer's default VBScript version, Microsoft
has implemented a JavaScript version. And once some hearty volunteer
steps up and implements a Perl script, Internet Explorer will
be able to understand that, as well. (The only caveat is that
the script executables must be registered on the local machine,
but this is a simple matter.)
Internet Explorer is not the only program to which Microsoft will
add OLE scripting. In future releases of NT, for instance, the
"shell" will be scriptable. (Windows users speak of
the "shell," a loose concept composed of utility tools
such as File Manager and Explorer. This is a far cry from the
command line interface that do-it-yourself UNIX users have come
to know and love.) Other programs will be enhanced, as well.
The original goal of the designers of the Basic programming language
as implemented at Dartmouth was to make a language that was easy
to learn, understand, and use. Microsoft continued that mission,
refining Basic into its current Visual Basic state. The Visual
Basic family employs an English-like syntax, so it's easy to start
working with any form of the language immediately.
Because VBScript is an interpreted language that the Internet
Explorer scripting engine understands, there is no need for a
VBScript compiler or similar development tool. With Internet
Explorer 3.x installed, the appropriate VBScript DLLs are in the
machine's \System32 directory. All you need to start scripting,
then, is an editor such as WordPad or ActiveX Control Pad.
Let's examine the format of a Visual Basic Script as it appears
in an HTML page, look at some sample output, and then proceed
to the nitty-gritty of VBScript syntax.
To use a VBScript in an HTML page, the script must be started
with the <SCRIPT LANGUAGE="VBScript"> tag. The
following example script writes two lines to the screen, as illustrated
in Figure 2.1.
Figure 2.1 : Output From A Simple Vbscript.
<HTML>
<HEAD>
<TITLE>VBScript Simple</TITLE>
</HEAD>
<BODY>
<B>Test Document</B><BR>
start
<HR>
<SCRIPT LANGUAGE="VBScript">
<!--
document.write "<B>" & window.name & "</B><BR>"
document.write "VBScript Simple<BR>"
-->
</SCRIPT>
<HR>
end
</BODY>
</HTML>
The LANGUAGE="VBScript" portion of the <SCRIPT>
tag is necessary because Explorer can use other script languages.
The comment tags (<!-- and -->) are not required but are
used to prevent browsers that don't understand script tags from
displaying the embedded code.
The above script could go in either the <BODY> or <HEAD>
portion of the HTML document. Later in the chapter, we'll show
you some scripts that refer to form objects within an HTML document.
Scripts that refer to specific form objects must go in the body
of the page.
An HTML page can contain multiple <SCRIPTS>. For example,
a script in the <HEAD> section could set a few properties
of the page, as follows:
<HTML>
<HEAD>
<TITLE>VBScript Test</TITLE>
<SCRIPT LANGUAGE="VBScript">
<!--
document.bgcolor = "#Ø1ØØ11"
document.fgcolor = "#fffffØ"
-->
</SCRIPT>
</HEAD>
<BODY>
<H1>Multiple Script Sample</H1>
<SCRIPT LANGUAGE="VBScript">
<!--
MsgBox "Multiple scripts are confusing..."
-->
</SCRIPT>
</BODY>
</HTML>
This is a perfectly valid technique, although in general we find
it preferable to consolidate everything in one script.
As with Visual Basic, program statements in VBScript are terminated
by an end-of-line or by a colon (:). For example, the following
statement:
document.bgcolor = "#Ø1ØØ11" : document.fgcolor = "#fffffØ"
is equivalent to
document.bgcolor = "#Ø1ØØ11"
document.fgcolor = "#fffffØ"
Program lines may be continued on the next line with the underscore
(_) character, as follows:
document.bgcolor = _
"#Ø1ØØ11"
In terms of data typing, VBScript is a "loose" language.
There is only one type, variant, which can contain either
numeric or string data. Since there is only one type, variables
do not need to be declared before they are used. For complex scripts,
however, the Option Explicit flag can be set at the top of the
script, requiring variables to be declared before use with the
Dim statement. For example:
Option Explicit
Dim x
x = 1Ø
VBScript is different from a language like C or C++, where all
variables must be declared before they are used. Without the Dim
statement, the developer may unintentionally reuse a variable
that has been used elsewhere in the script. The Option Explicit
flag prevents such problems because a variable must have a Dim
statement, but only one.
VBScript attempts to interpret variables appropriately based on
how the variables were first set. Consider the following:
anum = 1
bnum = 2
atex = "abc"
btex = "def"
cnum = anum + bnum
Msgbox "anum+bnum=" & cnum
ctex = atex + btex
MsgBox "atex+btex=" & ctex
amix = anum + atex
MsgBox "anum+atex=" & amix
The first two message boxes appear with expected values (3 and
the string "abcdef"), but the third message box does
not. This sort of loose data typing can cause you headaches even
in the simplest of programs. Fortunately, variables in VBScript
all have a subtype, and the language also provides a series
of conversion functions.
If we change the third line in the above segment to read
amix = CStr(anum) + atex
MsgBox "anum+atex=" & amix
then the appropriate value, 1abc, will appear, because the Cstr
function converts the number to a string.
In addition to the integer subtype, numbers can also be of the
subtypes byte, long, single, double, or date/time. The date/time
subtype is best used with the various date or time functions.
The Now function, for instance, returns a string containing the
current date and time of the local machine, as in 5/16/96 7:35:28
PM. The Time and Date functions can be used to generate just the
current system time and date respectively. From these values,
specific pieces of the date or time can be extracted using the
appropriate functions.
Other subtypes include empty, null, Boolean, object, and error.
Variable names must be unique, must begin with an alphabetic character,
must be less than 256 characters, and cannot contain an embedded
period (.).
In terms of scope, variables are unique and local to the subroutine
or function in which they are declared. Global variables are declared
outside of any subroutine or function and are available to all
subroutines and functions within a script.
NOTE |
If multiple <SCRIPT>s occur within a page, values are not passed among them. Also, if a global variable is used inside a subroutine, the original global value is lost.
|
The following script illustrates these points:
<HTML>
<HEAD>
<BODY>
<TITLE>Test document</TITLE>
<SCRIPT LANGUAGE="VBScript">
avar = "avar inside head"
MsgBox avar
</SCRIPT>
</HEAD>
</BODY>
<SCRIPT LANGUAGE="VBScript">
document.write "testform" & "<HR>"
MsgBox "value of avar from head script: " & avar
avar = "inside main of 2nd script"
MsgBox "value of avar in body script: " & avar
Call Varsub
MsgBox "after subroutine: " & avar
Sub VarSub
avar = " inside subroutine"
MsgBox "value of avar in subroutine: " & avar
End Sub
</SCRIPT>
</BODY>
</HTML>
Thus far we have only discussed variables with a single value-scalar
variables. VBScript can also handle array variables.
Arrays can be declared with either a static or dynamic number
of elements, as follows:
Dim statArray(1Ø)
Dim dynArray()
It's a simple matter to initialize an array with a fixed list,
as follows:
Dim bigArray(5, 6, 7, 8, 9, 1Ø, 11, 12, 13, 14, 15)
Notice that the elements of bigArray can be referenced by a single
integer; hence, we say that bigArray is a one-dimensional array.
For example, bigArray(0) contains the value 5.
This brings us to the important observation that the default lower
bound of index offsets in Visual Basic is 0. However, many people
find this confusing, and elect to change the default lower bound
to 1, with the following statement in the Declarations section:
Option Base 1
It is often useful to set up a two-dimensional array (for example,
when representing cells in a grid), or a three-dimensional array
when representing a cube. In such arrays, the offset of an element
is a vector. A two-dimensional array's elements are referenced
by a two-dimensional vector offset, and so on for higher dimensions.
The same considerations apply to the index offset's default lower
bound.
Following is VBScript code to set up a two-dimensional (8 x 8)
chessboard grid, numbering the squares from 1 to 64. The script
sets colors on table cells using the <Font Color...> tags,
and on table cell backgrounds using <TD BGCOLOR...> tags.
It uses the Modulus operator to figure out if a given square should
have a black or a white background. Figure 2.2 shows the script
in action.
Figure 2.2 : The Chessboard Squares Are Properly Colored-Thanks
To The Tricky Modulus Operator.
<HTML>
<HEAD>
<TITLE>My Beautiful Chessboard</TITLE>
</HEAD>
<BODY>
<h1> My Beautiful Chessboard </h1>
<SCRIPT LANGUAGE="VBScript">
'
' Demo Script. 6/96
'
Dim X
Dim Y
WHITE = "ffffff>" ' this strange >
becomes clear in the concatenation code below
BLU = "ØØØØff>"
colornum = " " ' define this as a string
sqcolor = " "
Dim CArray(8, 8) ' a 2-dimensional array for the square numbers.
document.write "<CENTER>"
document.write "<TABLE border=4 padding=2>"
'
' The only trickiness is the mod (modulus) operator: if
' the array number minus the row number is odd, then make '
the square color black; otherwise make it white.
'
' Also: make use of FONT COLOR tag to set color of text
' within a Table Cell; make use of <TD BGCOLOR... '
tag to set the background color of the Table
' Cell.
For X = 1 to 8
For Y = 1 to 8 ' fill in the values of each square
CArray(X,Y) = ((X - 1) * 8) + Y
if ((CArray(X,Y) -X) mod 2 = 1) then
sqcolor = "ØØØØØØ"
colornum = "<font color=#" & WHITE &
CStr(CArray(X,Y)) & "</font>"
else
sqcolor = "ffffff"
colornum = "<font color=#" & BLU &
CStr(CArray(X,Y)) & "</font>"
end if
document.write "<TD bgcolor=#" & sqcolor & ">"
& colornum & "</td>"
Next
document.write "<tr>" ' must advance to next row
Next ' out of loop, just finish up the HTML.
document.write "</TABLE>"
document.write "</CENTER>" & "<hr>"
document.write "Next: write a chess-playing program."
</SCRIPT>
</BODY>
</HTML>
Theoretically, the array can accommodate up to 60 dimensions (although,
as Microsoft states, "most people can't comprehend more than
about three or four
").
Dynamic arrays can be resized with the ReDim statement, and the
original contents retained with the Preserve keyword. Here is
an example that uses the Ubound() function:
ReDim Preserve BiggerArray(Ubound(SmallerArray) + 1Ø)
This will create BiggerArray, with a size of 10 more elements
than SmallerArray, while saving the previous contents of SmallerArray.
On other occasions, you might just want to allocate elements to
an array with a ReDim statement as follows:
Dim MyArray(1Ø)
Dim X : X = 2Ø
ReDim MyArray(X + 1)
Test yourself: After the ReDim statement, how many integers does
MyArray now hold? If you remembered that Visual Basic's lower
index offset starts at 0 by default, you would answer correctly:
MyArray now holds not 21, but 22 elements!
NOTE |
The ReDim statement can only occur once in a procedure.
|
CAUTION |
In a multidimensional array, only the upper bound of the last dimension of the array can be increased or decreased.
|
VBScript supports the usual assortment of operators, including
arithmetic, comparison, and logical operators. The following table
of operators is adapted from the Microsoft documentation.
Table 2.1 VBScript Operators
Arithmetic Operators | Symbol
| Comparison Operators | Symbol
| Logical Operators | Symbol
|
Exponentiation | ^
| Equality | =
| Logical negation | Not
|
Unary negation | -
| Inequality | <>
| Logical conjunction | And
|
Multiplication | *
| Less than | <
| Logical disjunction | Or
|
Division | /
| Greater than | >
| Logical exclusion | Xor
|
Integer division | \
| Less than or equal to | <=
| Logical equivalence | Eqv
|
Modulo arithmetic | Mod
| Greater than or equal to | >=
| Logical implication | Imp
|
Addition | +
| Object equivalence | Is
| Subtraction | -
|
String concatenation | &
| | |
| |
Within an expression, operators are evaluated from left to right,
unless the expression contains mixed types. In that case, operators
are evaluated in the order of Table 2.1-arithmetic, then comparison,
and then logical. Parentheses can be used to enforce the order
of evaluation in unclear or complex statements. For example, X
= 5 - 3 * 2 evaluates to -1, but X = (5 - 3) * 2 evaluates to
4.
VBScript supports several fundamental branching statements. These
statements are sufficient to perform any sort of conditional logic
necessary.
This statement comes in two forms, single or multiline. The single-line
version omits the Else and End If keywords:
If [condition=TRUE] Then [statement(s)]
For example:
<SCRIPT LANGUAGE="VBScript">
Sub Test
x = document.TestForm.field1.Value
If IsNumeric(x) Then MsgBox "No numbers please"
End Sub
</SCRIPT>
<FORM NAME="TestForm">
<INPUT TYPE="TEXT" NAME="field1" onChange="Test">
<INPUT TYPE="TEXT" NAME="field2" onChange='If IsNumeric(field2.value) Then MsgBox "No numbers please"'>
</FORM>
Use the multiline syntax when you want more that one statement
to be executed after the conditional. Here's the same script,
but changed to illustrate the multiline syntax:
<SCRIPT LANGUAGE="VBScript">
Sub Test
x = document.TestForm.field1.Value
If IsNumeric(x) Then
MsgBox "No numbers please"
MsgBox "I mean it!"
Else
MsgBox "You got it right"
End If
End Sub
</SCRIPT>
Statements can be nested to as many levels as needed:
<SCRIPT LANGUAGE="VBScript">
<!--
Sub Test
x = document.TestForm.field1.Value
If IsNumeric(x) Then
If x > 1ØØ Then
MsgBox "Too high"
ElseIf x < 5Ø Then
MsgBox "Too low"
ElseIf x > 49 And x < 1Ø1 Then
MsgBox "Close enough"
End If
Else
MsgBox "Enter a number"
End If
End Sub
-->
</SCRIPT>
NOTE |
When nesting multiple If statements, each If statement requires a corresponding End If statement.
|
Do... Loop branching statements are available in various forms:
Do While [condition=TRUE]
[statement(s)]
Loop
Do [statement(s)]
Loop While [condition=TRUE]
Do Until [condition=TRUE]
[statement(s)]
Loop
Do [statement(s)]
Loop Until [condition=TRUE]
The first example shows a simple
Do...While loop to print a series of numbers in a table:
<SCRIPT LANGUAGE="VBScript">
document.write "<TABLE BORDER=1><TR>"
c = 1ØØØ
Do While c < 1ØØØ1
document.write "<TD>" & c & "</TD>"
c = c + 1ØØØ
Loop
document.write "</TR></TABLE>"
</SCRIPT>
Here's an example that uses Until to create a multiplication table,
illustrated in Figure 2.3:
Figure 2.3 : Output Showing Multiplication Table.
<SCRIPT LANGUAGE="VBScript">
document.write "<TABLE BORDER=1><TR>"
d = 1
Do
c = 1
Do While c < 11
f = c * d
document.write "<TD>" & f & "</TD>"
c = c + 1
Loop
document.write "</TR><TR>"
d = d + 1
Loop Until d > 1Ø
document.write "</TR></TABLE>"
</SCRIPT>
These various forms of looping are different in terms of when
and how the condition is tested. In addition, the Exit keyword
can be used to drop out of a loop as needed. For example:
<SCRIPT LANGUAGE="VBScript">
document.write "<TABLE BORDER=1><TR>"
c = Ø
Do Until c = 11
document.write "<TD>" & c & "</TD>"
c = c + 1
If c = 7 Then Exit Do
Loop
document.write "</TR></TABLE>"
</SCRIPT>
The third type of branching statement is a For...Next loop, which
allows a block of code to be executed a specific number of times
by using a loop-control variable. This example generates a random
table of colors:
<SCRIPT LANGUAGE="VBScript">
' Assign an arbitrary starting color
v = 5Ø5Ø5Ø
document.write "<TABLE BORDER=1 cellpadding=1Ø><TR>"
for w = 1 to 2Ø
y = v * w
document.write "<TD BGCOLOR=#" & y & ">.</TD>"
If w mod 5 = Ø Then
document.write "</TR><TR>"
next
document.write "</TR></TABLE>"
</SCRIPT>
The Step keyword can be used to increase the increment in the
For statement. For instance, the statement
For w = 1 to 2Ø Step 5
would increment the counter by 5 for each loop.
The For Each syntax can be used to loop through an array:
<SCRIPT LANGUAGE="VBScript">
Dim v(4)
Dim w
for x = 1 to 1Ø
y = 1Ø * x
v(x) = y
next
document.write "<TABLE BORDER=1 cellpadding=1Ø><TR>"
For Each w in v
document.write "<TD BGCOLOR=#" & w & ">.</TD>"
next
document.write "</TR></TABLE>"
</SCRIPT>
Two types of procedures are available in VBScript: subroutines
and functions. Parameters can be passed to both, but only functions
can return data. Both types of procedures must be declared before
they are used within a script.
Subroutines are declared as follows:
Sub [name]([ByVal] parameter1, [ByVal] parameter2, ...)
[statement(s)]
End Sub
Visual Basic, like many other programming languages, distinguishes
parameters passed by reference (functions can change the parameter's
value in memory) from parameters passed by value (only a copy
is passed to the subroutine; the original parameter's value stays
unchanged). As you can see in the preceding subroutine syntax,
the ByVal keyword declares parameters passed by value. The same
principle holds for functions, which we discuss in the next section.
If the subroutine has no arguments, the subroutine name can optionally
be followed with a pair of empty parentheses, (). The following
form and script present the user with an InputBox; each successive
word, followed by a space, is added to a variable:
<HTML>
<HEAD>
<TITLE>Test document</TITLE>
</HEAD>
<BODY>
<B>Word List Test</B><BR>
<FORM NAME="subroute1">
<INPUT TYPE="text" NAME="word" size="1Ø"><BR>
<INPUT TYPE="button" NAME="NewWord" VALUE="Add word">
<HR>
Current Word List:<BR>
<INPUT TYPE="text" NAME="WordList" SIZE=7Ø>
</FORM>
<SCRIPT LANGUAGE="VBScript">
Dim WordForm : Set WordForm = document.subroute1
Dim WordList
Dim ThisList
Dim NumElements : NumElements = Ø
Sub NewWord_onClick
If NumElements = Ø Then
Space = ""
Else
Space = " "
End If
If WordForm.word.value <> "" Then
NumElements = NumElements + 1
ThisList = ThisList & Space & WordForm.word.value
WordForm.WordList.value = ThisList
WordForm.word.value = ""
End If
End Sub
</SCRIPT>
</BODY>
</HTML>
Functions are declared as follows:
Function function-name([ByVal] parameter1, [ByVal] parameter2, ...)
[statement(s)]
End Function
The function's name is a special variable used to store the contents
of the function's return value. To put it another way, somewhere
inside the function it is expected that the function name will
be assigned a value; this is the function's return value.
As with subroutines, parameters are optional. The parameter name
is a placeholder local to the function. Remember that the ByVal
declaration is necessary if you want to make sure that the local
function does not have the ability to change a global variable's
value.
A function can either be positioned on the right side of an expression,
or evaluated inside an expression. In the following, note how
the special variable AddThree contains the return value of the
function:
<HTML>
<HEAD>
<TITLE>Function Example</TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="VBScript">
Dim Avar : Avar = 3
MsgBox "Avar=" & Avar
ReturnValue = AddThree(Avar)
MsgBox "AddThree=" & ReturnValue
MsgBox "AddThree=" & AddThree(Avar)
Function AddThree(Anumber)
AddThree = Anumber + 3
MsgBox "AddThree inside function=" & AddThree
End Function
</SCRIPT>
</BODY>
</HTML>
VBScript incorporates several dozen built-in functions. Table
2.2 lists these functions, roughly grouped by purpose.
Table 2.2 Built-in Functions
Arithmetic | Conversion
| String | Date/Time
| Array | Boolean
| Other |
Abs | Cbool | Asc
| Date | Array | IsArray
| CreateObject |
Atn | Cbyte | Chr
| Date-Serial | LBound
| IsDate | InputBox |
Cos | Cdate | InStr
| Date-Value | UBound | IsEmpty
| MsgBox |
Exp | CDbl | LCase
| Day | | IsNull
| VarType |
Hex | Clng | Left
| Hour | | IsNumeric
| |
Int, Fix | Csng | Len
| Minute | | IsObject
| |
Log | Cstr | LTrim
| Month | |
| |
Oct | Str | Mid
| Now | | |
|
Rnd | StrComp | Right
| Second | |
| |
Sgn | String | RTrim
| Time | | |
|
Sin | | Trim
| Time-Serial | |
| |
Sqr | | UCase
| TimeValue | |
| |
Tan | | Val |
WeekDay | | |
|
| | |
Year | | |
|
The Internet Explorer document container holds various objects
in addition to HTML data. These objects all have properties
that can be read or set; methods, which are actions that
can be scripted for the object; and events, or actions
that trigger code in a script to be executed.
You're undoubtedly already familiar with the Form object, which
in turn can access an Elements array. This Elements array contains
the "intrinsic" HTML controls-namely, the various types
of buttons, boxes, select lists, and so on, used within HTML forms.
The following sections explain how to use some of the most important
objects: Window, Document, Anchor, Link, and Form.
The Window object is the parent for all other objects, and refers
to the Explorer frame and all other objects contained within.
The following script demonstrates a few of these, and Figure 2.4
shows the confirmation box from the script.
Figure 2.4 : Selecting OK In This Confirmation Box Causes
The Script To Navigate To A New URL.
<HTML>
<HEAD>
<TITLE>Window Object Examples</TITLE>
</HEAD>
<BODY>
doc start<BR>
<SCRIPT LANGUAGE="VBScript">
Winname = window.name : document.write Winname & "<BR>"
Winloc = window.location : document.write Winloc & "<BR>"
alert "This is an Alert."
window.alert "Answer OK to the next box to go to homepage. Cancel to stay on this page"
conreturn = window.confirm("This is a confirmation.")
If (conreturn) Then
window.navigate "http://127.Ø.Ø.1/default.htm"
End If
</SCRIPT><BR>
doc end<BR>
</BODY>
</HTML>
This page first displays two lines of window information, followed
by two Alerts, followed by a Confirmation prompt. Clicking OK
returns True; that is, the variable conreturn is set to 1, and
the window.navigate statement in the If test is executed.
The Document object refers to the currently loaded HTML page.
Compare our next example to the Window object example just above,
and take note of two things. First, objects below the Window level
must be referenced with the appropriate object name. For instance,
in the preceding script the objects window.alert and alert
were equivalent. In the following script, however, fgcolor
will not work.
The second to note is that, when the document is first loaded,
any statements in the VBScript that write data to the window,
such as write statements or statements that set properties, are
only executed once. It is not possible (as the program now stands)
to have further code that rewrites various HTML elements within
the page-for example, to change the background color.
Also, notice that the last value set for a property is the one
that will apply to the page, overriding any previously set properties.
<HTML>
<HEAD>
<TITLE>Window Object Examples</TITLE>
</HEAD>
<BODY>
doc start<BR>
<SCRIPT LANGUAGE="VBScript">
document.bgcolor = "#ØØØØØØ"
window.document.fgcolor = "#ff2Ø3Ø"
document.fgcolor = "#fff111"
fgcolor = "#ffffff"
document.linkColor = "111111"
document.alinkColor = "222222"
document.vlinkColor = "333333"
</SCRIPT><BR>
doc end<BR>
</BODY>
</HTML>
The foregoing statements adjust the color properties of the window.
The colors are specified by a Red, Green, Blue (RGB) triplet of
hex values (ranging from 00 to FF for each primary color). For
example, "FFFFFF" is the maximum setting of Red, Green,
and Blue; when combined, this creates white. The opposite extreme
is "000000", the absence of all color, which appears
black.
The Location object is set to the value of the current URL (Uniform
Resource Locator). Resetting any portion of the URL causes Explorer
to attempt to navigate to the new location. For example:
<HTML>
<HEAD>
<TITLE>Location Object Example</TITLE>
</HEAD>
<BODY>
Home Page:
<A ID="Rad1" HREF="http://127.Ø.Ø.1/zd/chap2/locate2.htm">
<IMG SRC="wk.gif"></A>
<SCRIPT LANGUAGE="VBScript">
Sub Rad1_MouseMove(s,b,x,y)
temp = "/default.htm"
location.pathname = temp
End Sub
</SCRIPT>
</BODY>
</HTML>
Moving the mouse over the icon invokes the subroutine, which moves
to the new page when it encounters the location.pathname statement.
It is not possible (as the program now stands) to change more
than one property of the Location object, because the navigation
takes place immediately once any property is changed.
An anchor, in hypertext terminology, is a tag indicating
that some text or an image, or both, should be clickable to send
the user to another destination URL on the Internet.
In general, the HTML syntax for declaring and ending an anchor
is as follows:
<A HREF= [some internet destination]> [Clickable Object] </A>
For example, here is hyperlinked text:
<A HREF="http://www.link.com"> This text, if clicked, sends me to http://www.link.com </A>
The anchor declaration is coupled with a hypertext reference,
or HREF, indicating the destination if the user clicks the text.
The clickable ("hot") text ends when the end-anchor
</A> tag is encountered.
In VBScript, anchors in an HTML page can be referenced via the
array
documents.anchors().name
Here's an example:
<HTML>
<HEAD>
<TITLE>Location Object Example</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF">
<CENTER>
<TABLE BORDER=4><TR>
<TD><A NAME="KEY"><IMG SRC="key.gif"></A></TD>
<TD><A NAME="CAL"><IMG SRC="calendar.gif"></A></TD>
<TD><A NAME="MAIL"><IMG SRC="mail.gif"></A></TD>
<TD><A NAME="TIME"><IMG SRC="time.gif"></A></TD>
<SCRIPT LANGUAGE="VBScript">
document.write "</TR><TR>"
document.write "<TD>" & document.anchors(Ø).name & "</TD>"
document.write "<TD>" & document.anchors(1).name & "</TD>"
document.write "<TD>" & document.anchors(2).name & "</TD>"
document.write "<TD>" & document.anchors(3).name & "</TD>"
document.write "</TR></TABLE></CENTER>"
</SCRIPT>
</BODY>
</HTML>
There are no events associated with Anchors. That doesn't hold
true for Link objects, however, coming up next.
The Link object allows you to reference all of the links embedded
in a page via the array
document.links().[property]
In addition, two events are available for scripting with the Link
object: MouseMove, which triggers an event when the mouse cursor
moves over a link; and Click, which triggers an event when the
link is clicked.
Various properties of the links can also be accessed: HREF, host,
hostname, port, pathname, search, hash, and target. In this example,
as the mouse is moved over the various images, the text boxes
are updated to show the property data for the link. See Figure
2.5.
Figure 2.5 : Displaying Info From The Link Object In
A Text Box.
<HTML>
<HEAD>
<TITLE>Location Object Example</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF">
<FORM NAME="formone">
<A BORDER=Ø id="linkØ" HREF="http://KEYlink.orgnetedu.com/KEY.htm#keytop"><IMG SRC="key.gif"></A>
<A BORDER=Ø id="link1" HREF="http://CALlink.neworgedu.com/CAL.htm#caltop"><IMG SRC="calendar.gif"></A>
<A BORDER=Ø id="link2" HREF="http://MAILlink.edunetorg.com/MAIL.htm#mailtop"><IMG SRC="mail.gif"></A>
<A BORDER=Ø id="link3" HREF="http://TIMElink.neteduorg.com/TIME.htm#timetop"><IMG SRC="time.gif"></A>
<HR>
<TABLE BORDER=1>
<TR><TD>Href:</TD> <TD><INPUT TYPE="TEXT" NAME="dhref" size=4Ø></TD></TR>
<TR><TD>Host:</TD> <TD><INPUT TYPE="TEXT" NAME="dhost" size=4Ø></TD></TR>
<TR><TD>Hostname:</TD> <TD><INPUT TYPE="TEXT" NAME="dhostname" size=4Ø></TD></TR>
<TR><TD>Port:</TD> <TD><INPUT TYPE="TEXT" NAME="dport" size=4Ø></TD></TR>
<TR><TD>Pathname:</TD> <TD><INPUT TYPE="TEXT" NAME="dpathname" size=4Ø></TD></TR>
<TR><TD>Search:</TD> <TD><INPUT TYPE="TEXT" NAME="dsearch" size=4Ø></TD></TR>
<TR><TD>Hash:</TD> <TD><INPUT TYPE="TEXT" NAME="dhash" size=4Ø></TD></TR>
<TR><TD>Target:</TD> <TD><INPUT TYPE="TEXT" NAME="dtarget" size=4Ø></TD></TR>
</FORM>
<SCRIPT LANGUAGE="VBScript">
Sub linkØ_MouseMove(s,b,x,y)
SetLinkNumber(Ø)
End Sub
Sub link1_MouseMove(s,b,x,y)
SetLinkNumber(1)
End Sub
Sub link2_MouseMove(s,b,x,y)
SetLinkNumber(2)
End Sub
Sub link3_MouseMove(s,b,x,y)
SetLinkNumber(3)
End Sub
Sub SetLinkNumber(linknumber)
document.formone.dhref.value = document.links(linknumber).href
document.formone.dhost.value = document.links(linknumber).host
document.formone.dhostname.value = document.links(linknumber).hostname
document.formone.dport.value = document.links(linknumber).port
document.formone.dpathname.value = document.links(linknumber).pathname
document.formone.dsearch.value = document.links(linknumber).search
document.formone.dhash.value = document.links(linknumber).hash
document.formone.dtarget.value = document.links(linknumber).target
End Sub
</SCRIPT>
</BODY>
</HTML>
The Form object will likely become your best friend-in particular,
the Elements array. This array consists of the familiar buttons,
text boxes, drop-down lists, and so on, that you are accustomed
to seeing in an HTML form. With Internet Explorer, these elements
are now scriptable objects, not just static items hardcoded into
a page.
This next example demonstrates changing the values of text boxes
and buttons based on user actions. See Figure 2.6.
Figure 2.6 : Changing The Display Of Text Boxes And Buttons.
<HTML>
<HEAD>
<TITLE>Form Object Example</TITLE>
</HEAD>
<FORM NAME="FormObj">
<INPUT TYPE="BUTTON" NAME="Button1" Value="ON"><BR>
<INPUT TYPE="RADIO" NAME="RadioGroup" onClick="RadioGroup">This doesn't work of course...<BR>
<HR>
Click here: <INPUT TYPE="TEXT" NAME="MessageIn" SIZE="3Ø"> type something<BR>
and hit the Tab key.
<HR>
<CENTER>Message Bar<BR>
<INPUT TYPE="TEXT" NAME="MessageBar" SIZE="6Ø"><BR>
Here's what you typed:<BR>
<INPUT TYPE="TEXT" NAME="MessageBar2" SIZE="6Ø"><BR>
</FORM>
<SCRIPT LANGUAGE="VBScript">
SUB RadioGroup
MsgBox "in radio sub"
END SUB
Sub Button1_onClick
If document.FormObj.Button1.value = "ON" Then
document.FormObj.Button1.value = "OFF"
Else
document.FormObj.Button1.value = "ON"
End If
End Sub
Sub MessageIn_onBlur
document.FormObj.MessageBar.value = "Ok, you've left the box..."
End Sub
Sub MessageIn_onFocus
document.FormObj.MessageBar.value = "Ok, you're focused in the box..."
End Sub
Sub MessageIn_onChange
document.FormObj.MessageBar2.value = document.FormObj.MessageIn.value
End Sub
</SCRIPT>
</BODY>
</HTML>
In the upcoming section of sample applications, you'll find additional
examples of using the intrinsic controls, including manipulating
another object within a form. And, although currently only the
value of an intrinsic control can be altered, Microsoft
has promised to deliver methods of refreshing or redrawing a document
in place.
The Error object can be used to cause an error in the script,
displaying a message box with the specified text when the Raise
method is called. For example:
<HTML><BODY><SCRIPT LANGUAGE=VBSCRIPT>
clErrNumber=CLng(1)
MsgBox "Before Err method"
Err.Description="Sample Error Message"
Err.Raise(clErrNumber)
MsgBox "This Box Won't show"</SCRIPT></BODY></HTML>
This displays an error message box containing the message we have
assigned to the Error object. It also causes the script to abort.
This section contains some small applications we developed while
testing the functionality of the documented pieces of VBScript.
In our first example, we prompt for the age of the end-user and
figure out if it's a reasonable entry. If the number seems reasonable,
we display the birth year. Let's consider the case of a realistic
entry, 44. Figure 2.7 shows the input screen.
Figure 2.7 : The User Enters 44; This Number Seems Reasonable.
Given that the input meets our criterion (you'll see later in
the code that we permit the user to be up to 120 years old), we
calculate the year of birth as the user's input subtracted from
the current year. Then we display the birth year (Figure 2.8).
Figure 2.8 : The Program Figures Out That The User Was
Born In 1952.
Now let's look at the code for this simple application, WHEN.HTM,
Listing 2.1. It demonstrates the useful and necessary technique
of data-type conversion.
Listing 2.1 WHEN.HTM
<BASE HREF="file:///C|/INETSDK/SAMPLES/VBSCRIPT/WHEN.HTM">
<HTML><SCRIPT LANGUAGE="VBScript">
Sub When() Dim F,TDate Set F = document.frmMain
TDate = CInt(F.txtAge.Value) ' the user's input
TDate2 = CInt(Right(Date,2)) ' the last 2 digits of curr year
TDate2 = CInt("19") & TDate2 ' assume this century
If TDate > 12Ø Then MsgBox "Are you dead?"
Exit Sub End If
TDate = TDate2 - Tdate ' subtract user input from curr year
MsgBox "You were born in " & CStr(TDate)End Sub
</SCRIPT>
<H2> Fun with VB! </H2>
<HR>
<FORM NAME=frmMain>
Enter your age ==> <INPUT NAME=txtAge TYPE=TEXT>
<INPUT TYPE=BUTTON NAME=btnWhen Value="When was I born?" onClick="When()">
</CENTER>
</FORM></HTML>
The user fills out the form variable, and when it is submitted
(the onClick action) the When() routine is called. When() is careful
to change all variables to an Integer data type, in order to do
arithmetic. For example, when it compares the user input to the
maximum permissible value of 120, the user's input has already
been converted to integer. Likewise, when it subtracts a valid
user input from the current year, both terms in the subtraction
have been converted to integer; otherwise, we'd get a run-time
error of a data type mismatch.
VBScript makes it a straightforward process to present an order-entry
form that the client can fill out. The user enters information
and then presses some type of "submit order" to declare,
in effect, that the transaction is complete. Furthermore, VBScript
can quite easily perform client-side validation on the order data,
so that invalid data is given back to the client for cleanup to
avoid unnecessary intermediate round-trip transmissions to the
server.
For example, Figure 2.9 shows a computer order form where the
user has not yet filled in the required credit card information.
The Visual Basic script, embedded in the HTML, intercepts the
incomplete request and immediately sends a MsgBox informing the
user to fill in the required data, as shown in Figure 2.10.
Figure 2.9 : The User Tries To Submit This Incomplete
Order, And Figure 2.10 Is The Result.
Figure 2.10: The Customer Now Can Correct The Information
And Resubmit It; In This Way, The Server Only. Needs To Process
Valid Orders.
Let's take a look at the code for this form, ORDER.HTM, Listing
2.2, to see how the script accomplishes these goals.
Listing 2.2 ORDER.HTM
<BASE HREF="file:///C|/INETSDK/SAMPLES/VBSCRIPT/ORDER.HTM">
<HTML><CENTER><TITLE>Joe's Computer Shack!</TITLE>
<SCRIPT LANGUAGE="VBScript">
Dim CardType, CardNum, ExpDateDim mProc,mDisk,mMonitor,mRam'
' set up l1 via a series of concatenations (the form variables, after they've
' been validated) and then display it to the user via MsgBox.
'
Sub DoOrder()
Dim l1,l2,l3,l4,l5 Dim F Set F = document.frmMain ' capture the form
variables l1 = ("Thank you for your
order " & CHR(1Ø) & "" ) l1 = l1 & ("We have charged this order to your " & CardType & " Card." &
Chr(1Ø) & "") l1 = l1 & ("Your
order of a " & mProc & " with a " &
CHR(1Ø) & mDisk & " disk," &
mMonitor & "," & mRam & "Ram" & Chr(1Ø) &
"" ) l1 = l1 & ("Will be shipped to " & CHR(1Ø) &
F.txtShipto.Value & CHR(1Ø) ) l1 = l1 & (F.txtStreet.Value &
CHR(1Ø)) l1 = l1 & (l5 & F.txtAddress.Value)
MsgBox l1
End Sub'
' now a series of routines to set memory variables equal to user
' input immediately after they fill in particular form variables.
'
Sub SetProc(cProc) mProc = cProcEnd Sub
Sub SetDisk(cDisk) mDisk = cDiskEnd Sub
Sub SetMonitor(cMonitor) mMonitor = cMonitorEnd Sub
Sub SetRam(cRam) mRam = cRamEnd Sub'
' rudimentary validation is illustrated on the Card Number and the
' Expiration Date. Show MsgBox on failure. If all OK, call DoOrder()
' and echo back to the user the successful order.
'Sub GetCardInfo() CardNum = document.frmMain.txtCardNumber.Value
ExpDate =
document.frmMain.txtExpdate.value If CardNum = ""
Then MsgBox "You must enter your card number!" Exit
Sub End If If ExpDate = "" Then
MsgBox "You must enter the credit card's expiration date!" Exit Sub
End If
Call DoOrder()
End Sub
Sub SetCardType(cType) CardType = cTypeEnd Sub
</SCRIPT>
<FONT FACE="New Times Roman" SIZE=4>
<MARQUEE XWIDTH=1ØØ DIRECTION=LEFT ALIGN=MIDDLE FGCOLOR=GREEN
BGCOLOR=Yellow>Joe's Computer Shack.........What a deal!!!</MARQUEE></FONT></CENTER>
<HR>
<FORM NAME="frmMain"><CENTER><TABLE XBORDER=1
BGCOLOR="#FFFFCC" WIDTH=18Ø ALIGN=LEFT><TR><TD BGCOLOR=NAVY
ALIGN=CENTER><FONT
COLOR=FFFFCC>Processors</TD></TR><TR><TD><INPUT TYPE=RADIO
NAME=rProcs onClick="SetProc('Pentium 133')">P133
</TD></TR><TR><TD><INPUT TYPE=RADIO NAME=rProcs
onClick="SetProc('Pentium 166')">P166
</TD></TR><TR><TD><INPUT TYPE=RADIO NAME=rProcs
onClick="SetProc('Pentium Pro 166')">Pro166
</TD></TR><TR><TD><INPUT TYPE=RADIO NAME=rProcs
onClick="SetProc('Pentium Pro 2ØØ')">Pro2ØØ
</TD></TR></TABLE> <TABLE XBORDER=1 BGCOLOR="#FFFFFF"
WIDTH=19Ø ALIGN=LEFT><TR><TD BGCOLOR=RED ALIGN=CENTER><FONT
COLOR=FFFFCC>Hard Disks</TD></TR><TR><TD><INPUT TYPE=RADIO
NAME=rDisks onClick="SetDisk('1.1 GIG')">1.1 GIG
</TD></TR><TR><TD><INPUT TYPE=RADIO NAME=rDisks
onClick="SetDisk('1.6 GIG')">1.6 GIG
</TD></TR><TR><TD><INPUT TYPE=RADIO NAME=rDisks
onClick="SetDisk('2.1 GIG')">2.1 GIG
</TD></TR><TR><TD><INPUT TYPE=RADIO NAME=rDisks
onClick="SetDisk('2.7 GIG')">2.7 GIG </TD></TR></TABLE>
<TABLE XBORDER=1 BGCOLOR="#FFFFAA" WIDTH=19Ø
ALIGN=LEFT><TR><TD BGCOLOR=LightGreen ALIGN=CENTER><FONT
COLOR=BLUE>Monitors</TD></TR><TR><TD><INPUT TYPE=RADIO
NAME=rMonitors onClick="SetMonitor('14in SVGA')">14" SVGA
</TD></TR><TR><TD><INPUT TYPE=RADIO NAME=rMonitors
onClick="SetMonitor('15in SVGA')">15" SVGA
</TD></TR><TR><TD><INPUT TYPE=RADIO NAME=rMonitors
onClick="SetMonitor('17in SVGA')">17" SVGA
</TD></TR><TR><TD><INPUT TYPE=RADIO NAME=rMonitors
onClick="SetMonitor('21in SVGA')">21" SVGA
</TD></TR></TABLE> <TABLE XBORDER=1 BGCOLOR="Cyan"
WIDTH=2ØØ ALIGN=LEFT > <TR><TD BGCOLOR=White
ALIGN=CENTER><FONT
COLOR=BLACK>RAM</TD></TR><TR><TD><INPUT TYPE=RADIO NAME=rRam
onClick="SetRam('8 Meg')">8 Meg 4x36
</TD></TR><TR><TD><INPUT TYPE=RADIO NAME=rRam
onClick="SetRam('8 Meg EDO')">8 Meg 4x36 EDO
</TD></TR><TR><TD><INPUT TYPE=RADIO NAME=rRam
onClick="SetRam('16 Meg')">16Meg 4x36
</TD></TR><TR><TD><INPUT TYPE=RADIO NAME=rRam
onClick="SetRam('16 Meg EDO')">16Meg 4x36 EDO
</TD></TR></TABLE> </CENTER>
<BR><BR><BR><BR><BR><BR>
<HR><PRE>
Ship To:<INPUT TYPE=TEXT NAME=txtShipto Size=2Ø>Street :<INPUT TYPE=TEXT
NAME=txtStreet Size=2Ø>Address:<INPUT TYPE=TEXT NAME=txtAddress
Size=2Ø></PRE><FONT="Roman" SIZE=4>CreditCard Type
<TABLE XBORDER=1 BGCOLOR="White" WIDTH=2ØØ
ALIGN=LEFT><TR><TD><INPUT TYPE=RADIO NAME=rCardType
onClick="SetCardType('Visa')">Visa
</TD></TR><TR><TD><INPUT TYPE=RADIO NAME=rCardType
onClick="SetCardType('MasterCard')">MasterCard
</TD></TR><TR><TD><INPUT TYPE=RADIO NAME=rCardType
onClick="SetCardType('American Express')">Amex
</TD></TR><TR><TD><INPUT TYPE=RADIO NAME=rCardType
onClick="SetCardType('Discover')">Discover
</TD></TR></TABLE> Card No. <INPUT TYPE=TEXT NAME=txtCardNumber
>Exp Date <INPUT TYPE=TEXT NAME=txtExpDate><BR> <INPUT TYPE=BUTTON
NAME=btnOrder VALUE=Order ALIGN=LEFT
onClick="GetCardInfo()"><BR></FORM> </HTML>
The script in Listing 2.2 presents a form to the user and calls
it frmMain. The script is actually written above the HTML that
creates the form; examine the following line:
Set F = document.frmMain
This assigns variable F to the form frmMain; in this way, we can
reference the various fields of the form relative to F-for instance,
F.txtShipto.Value.
The logic flow here is straightforward: The user enters the data
(presented in a series of HTML tables); as radio buttons are clicked,
small procedures are called to store the order data in memory
variables. When the user is satisfied the order is complete, the
Order button is pressed. At this point, the subroutine GetCardInfo()
is called to demonstrate simple validation of the credit card
information. If all is well, the formatting routine DoOrder()
is called to echo to the user the successful input-and, of course,
to send the data to the Web server in a real application. Figure
2.11 shows the aftermath of a successful order.
Figure 2.11: The Doorder() Routine Formats A Summary
Of The Successful Order For The Customer.
You can manipulate controls inserted into HTML documents with
the <OBJECT> tag, by altering the value of the various parameters.
The Label control in the Microsoft ActiveX Gallery, for example,
is scriptable. This next script (Listing 2.3) allows the user
to change the text, angle, and font size of the label. See Figure
2.12.
Figure 2.12: Manipulating The Label Control With Vbscript.
Listing 2.3 LABEL.HTM
<!-- label.htm -->
<HTML>
<HEAD>
<TITLE>Label Control</TITLE>
</HEAD>
<BODY BGCOLOR=#FFFFFF TEXT=#ØØØØØØ>
<FONT FACE=ARIAL SIZE=2>
<CENTER>
<OBJECT classid="clsid:99B4212Ø-6EC7-11CF-A6C7-ØØAAØØA47DD2"
id=lblAct
width=3ØØ
height=1ØØ
align=center
hspace=1
vspace=1
>
<PARAM NAME="Angle" value="Ø" >
<PARAM NAME="alignment" value="Ø">
<PARAM NAME="BackStyle" value="Ø">
<PARAM NAME="Caption" value="Simplex Label">
<PARAM NAME="FontName" value="Lucida Handwriting">
<PARAM NAME="FontSize" value="4Ø">
<PARAM NAME="frcolor" value="16733935">
</OBJECT>
</CENTER>
<HR>
<FORM NAME="LabelControls">
<TABLE BORDER=Ø>
<TR>
<TD>Text:</TD><TD><INPUT TYPE=TEXT NAME=VarText SIZE=2Ø VALUE="Overwrite this"></TD>
</TR>
<TR>
<TD>Angle:</TD><TD><INPUT TYPE=TEXT NAME=VarAngle SIZE=4 VALUE="Ø"></TD>
</TR>
<TD>FontSize:</TD><TD><INPUT TYPE=TEXT NAME=VarFont SIZE=3 VALUE="1Ø"></TD>
</TR>
</TABLE>
<INPUT TYPE="BUTTON" NAME="cmdUpdate" VALUE="Rearrange"><BR>
</FORM>
<HR>
<SCRIPT LANGUAGE="VBScript">
Sub cmdUpdate_onClick
Dim TheForm
Set TheForm = Document.LabelControls
lblAct.Angle = TheForm.VarAngle.Value
lblAct.FontSize = TheForm.VarFont.Value
lblAct.Caption = TheForm.VarText.Value
End Sub
</SCRIPT>
</BODY>
</HTML>
Another example, TIMER.HTM (Listing 2.4) uses Microsoft's inTimer.ocx
to change the label at regular intervals. The inTimer.ocx causes
the parameters in the label control to update at specified intervals,
creating a simple animation effect. This script draws a pleasing
"Slinky"-like pattern, soothing the overstressed VBScripter
with a gently moving display of changing color and size (Figure
2.13).
Figure 2.13: Animating A Label By Resetting The Parameters.
Listing 2.4 TIMER.HTM
<!-- timer.htm -->
<HTML>
<HEAD>
<TITLE>Label Timer Example</TITLE>
</HEAD>
<BODY BGCOLOR="#ffffff">
<CENTER>
<OBJECT classid="uuid:99B4212Ø-6EC7-11CF-A6C7-ØØAAØØA47DD2"
id="LabOne" height="3ØØ" width="6ØØ"
>
<PARAM NAME="CAPTION" value="/\/\/\/\/\/\/\/\/\/\/\/\/\/\">
<PARAM NAME="FontName" value="Arial">
<PARAM NAME="FontSize" value="5">
<PARAM NAME="FontBold" value="1">
<PARAM NAME="ANGLE" value="Ø">
<PARAM NAME="ALIGNMENT" value="2">
<PARAM NAME="frcolor" value="Ø">
</OBJECT>
</CENTER>
<OBJECT classid="clsid:59CCB4AØ-727D-11CF-AC36-ØØAAØØA47DD2"
id="ItsAbout" align="middle"
>
<PARAM NAME="TimeOut" value="5Ø">
<PARAM NAME="enable" value="1">
</OBJECT>
<SCRIPT LANGUAGE="VBScript">
Dim Xcolor : Xcolor = Ø
Dim Xsize : Xsize = 5
Dim SizeFactor : SizeFactor = 1Ø
Dim MaxSize : MaxSize = 24Ø
Sub ItsAbout_Time
Dim Angle
Angle=LabOne.Angle
Xcolor = Xcolor + 843.7
LabOne.forecolor = Xcolor
If Xcolor > 9999999 Then
Xcolor = Ø
End If
XSize = XSize + SizeFactor
LabOne.FontSize = XSize
If XSize > MaxSize Then
SizeFactor = SizeFactor * -1
End If
If XSize < 1 Then
SizeFactor = SizeFactor * -1
End If
Angle=Angle+1
If Angle>1 then
Angle=Ø
End If
LabOne.Angle=Angle
End Sub
</SCRIPT>
</BODY>
</HTML>
In the next two examples, Listings 2.5 and 2.6, we use an SQL
table generated from an IIS access log. The first example also
employs the graph32.ocx that comes with Visual Basic. The IDC
file is called from a simple HTML form:
Listing 2.5 GRAPH.HTM
<!-- graph.htm -->
<HTML>
<HEAD>
<TITLE>SQL Query with Graph</TITLE>
</HEAD>
<BODY>
<H1>SQL Query with Graph</H1>
<BR>
<FORM METHOD=POST ACTION="/scripts/zd/chap2/graph.idc">
<B>Click the button for today's report:</B><BR><BR>
<INPUT TYPE=SUBMIT VALUE="Display Report">
</FORM>
</BODY>
</HTML>
Then the IDC file, graph.idc, executes the following
SQL statement:
Datasource: www_db
Template: graph.htx
Username: sa
SQLStatement:
+select
+target, 'FileCount' = count(Target), 'ByteSum' =
+sum(bytessent)
+FROM wwwtabØ1
+
+group by target
+order by ByteSum desc
The output includes only the first ten records returned from the
SQL query and is produced by the following HTX template file,
which also includes the <OBJECT> reference to the graph32.ocx
as shown in Figure 2.14.
Figure 2.14: A Graph Created With Graph32.Ocx Output
Using Data From The SQL Query.
Listing 2.6 GRAPH.HTX
<!-- graph.htx -->
<HTML>
<HEAD>
<TITLE>Summary HTTP Log Report Sample</TITLE>
</HEAD>
<BODY>
<B>Summary HTTP Log Report Sample</B>
<HR>
<TABLE BORDER=1 CELLPADDING=4>
<TR><TD>FileName</TD><TD>Accesses</TD><TD>Total Bytes</TD></TR>
<%begindetail%>
<%if CurrentRecord EQ 1Ø %>
</TABLE>
<%else%>
<TR>
<TD ALIGN=RIGHT><%Target%></TD>
<TD><%FileCount%></TD>
<TD><A HREF="<%ByteSum%>"><%ByteSum%></A></TD>
</TR>
<%enddetail%>
</TABLE>
<%endif%>
<OBJECT CODE="graph32.ocx"
CLASSID="clsid:Ø842D1ØØ-1E19-1Ø1B-9AAF-1A1626551E7C"
HEIGHT=24Ø WIDTH=27Ø ID=gphData
>
</OBJECT>
<SCRIPT LANGUAGE="VBScript">
Dim counter
counter=1
gphData.NumPoints=1Ø
Do While counter < 1Ø
temp = CInt(counter)
gphData.ThisPoint=temp
gphData.GraphData=document.links(temp).href
counter = counter + 1
Loop
</SCRIPT>
</BODY>
</HTML>
NOTE |
In order to have data to supply to graph32.ocx, we resorted to an interesting workaround: making links out of one column of data, then getting that data via the Link object. There's nothing "wrong" with this approach, but a user clicking on one of those links will get a 404 error message. As VBScript evolves, doubtless there will be many cleaner alternatives.
|
The final example, in Listings 2.7 and 2.8, builds on the Microsoft
example of a client-side image map to give the user a method of
creating a simple SQL query by selecting fields from an image.
As the user adds fields, the current query is displayed in a text
box beneath the image (Figure 2.15).
Figure 2.15: A Client-Side Image Map Used To Form An
SQL Query.
The initial HTML file is coded as follows. (Only the first column
is implemented in the source code listing.)
Listing 2.7 MAP.HTM
<!-- map.htm -->
<HTML>
<HEAD>
<TITLE>Client Side Image Map</TITLE>
</HEAD>
<BODY BGCOLOR="#ØØØØØØ" TEXT="#FFFFFF">
<CENTER><B>QueryMap</B><BR>
<A ID="myMap" HREF="/zd/chap2/map2.htm">
<IMG SRC="tablemap.gif" alt="Simple Image Map" BORDER=Ø></A></CENTER>
<HR>
<FORM NAME="QueryForm" METHOD="POST" ACTION="/scripts/zd/chap2/map2.idc">
<TABLE BORDER=1>
<TR><TD>Current Selection:</TD><TD><INPUT TYPE="TEXT" NAME="TextBox" size=2Ø></TD>
</TR>
<TR><TD>Current Query:</TD><TD>
<INPUT TEXTAREA NAME="QueryBox" SIZE="7Ø,1"
MAXLENGTH="7Ø"></TEXTAREA></TD></TR>
<TR>
<TD><INPUT TYPE="SUBMIT" NAME="SubmitButton" VALUE="Exec Query">
<INPUT TYPE="BUTTON" NAME="ResetQuery" VALUE="Reset Query" onClick=ResetQuery>
Mouse position: <INPUT TYPE="TEXT" NAME="MouseX" size=3>,
<INPUT TYPE="TEXT" NAME="MouseY" size=3>
</TD></TR>
</TABLE></FORM>
<SCRIPT LANGUAGE="VBScript">
<!--
Dim mX : Dim mY
Dim x : Dim y
Dim MouseX : Dim MouseY
Dim QueryString
Dim FirstField
FirstField = TRUE
Dim FirstString
FirstString = ""
Dim myForm : Set myform = Document.QueryForm
Sub myMap_MouseMove(s, b, x, y)
mX = x : mY = y
myForm.MouseX.value = mX : myForm.MouseY.value = mY
If InRect(x, y, Ø, Ø, 2ØØ, 3Ø) Then : SetTextBox("ClientHost")
ElseIf InRect(x, y, Ø, 3Ø, 2ØØ, 6Ø) Then : SetTextBox("Logtime")
ElseIf InRect(x, y, Ø, 6Ø, 2ØØ, 9Ø) Then : SetTextBox("ServerIP")
ElseIf InRect(x, y, Ø, 9Ø, 2ØØ, 12Ø) Then : SetTextBox("BytesSent")
ElseIf InRect(x, y, Ø, 12Ø, 2ØØ, 15Ø) Then : SetTextBox("Operation")
' These should work, but don't.
' ElseIf InRect(x, y, 2Ø1, Ø, 4ØØ, 3Ø) Then : SetTextBox("Username")
' ElseIf InRect(x, y, 2Ø1, 3Ø, 4ØØ, 6Ø) Then : SetTextBox("Service")
Else
myForm.TextBox.value = ""
End If
End Sub
Sub SetTextBox(Fieldname)
myForm.TextBox.value = Fieldname
End Sub
Sub myMap_OnClick
If FirstField = TRUE Then : FirstField = FALSE : FirstString = ""
Else : FirstString = ", "
End If
If InRect(mX, mY, Ø, Ø, 2ØØ, 3Ø) Then : SetQuerys("ClientHost")
ElseIf InRect(mX, mY, Ø, 3Ø, 2ØØ, 6Ø) Then : SetQuerys("LogTime")
ElseIf InRect(mX, mY, Ø, 6Ø, 2ØØ, 9Ø) Then : SetQuerys("ServerIP")
ElseIf InRect(mX, mY, Ø, 9Ø, 2ØØ, 12Ø) Then : SetQuerys("BytesSent")
ElseIf InRect(mX, mY, Ø, 12Ø, 2ØØ, 15Ø) Then : SetQuerys("Operation")
' ElseIf InRect(mX, mY, 2Ø1, Ø, 4ØØ, 3Ø) Then : SetQuerys("Username")
' ElseIf InRect(mX, mY, 2Ø1, 3Ø, 4ØØ, 6Ø) Then : SetQuerys("Service")
Else : myForm.QueryBox.value = QueryString
End If
End Sub
Sub SetQuerys(fieldname)
QueryString = QueryString + FirstString + fieldname
myForm.QueryBox.value = QueryString
End Sub
Sub ResetQuery_onClick
QueryString=""
myForm.QueryBox.value = QueryString
FirstField=TRUE
End Sub
Function InRect(x, y, lx1, ly1, lx2, ly2)
InRect = x>=lx1 AND x<=lx2 AND y>=lx1 AND y<=ly2
End Function
-->
</SCRIPT>
</BODY>
</HTML>
After the user clicks on the Exec Query button, the IDC
file, map.idc, and HTX files are called.
Datasource: www_db
Template: map.htx
Username: sa
MaxRecords: 5Ø
SQLStatement:
+select
+%QueryBox%
+FROM wwwtabØ1
The HTX file (Listing 2.8) makes use of the <%if%> statement
to determine which column headings to display, and which data
fields are returned from the SQL query.
Listing 2.8 MAP.HTX
<!-- map.htx -->
<HTML>
<HEAD>
<TITLE>Client Side Image Map Sample</TITLE>
</HEAD>
<BODY BGCOLOR="#ØØØØØØ" TEXT="#FFFFFF">
<B>HTTP Log Report Sample</B>
<HR>
<TABLE BORDER=1>
<%if ClientHost GT ""%><TD>ClientHost</TD><%endif%>
<%if LogTime GT ""%><TD>LogTime</TD><%endif%>
<%if ServerIP GT ""%><TD>ServerIP</TD><%endif%>
<%if BytesSent GT ""%><TD>BytesSent</TD><%endif%>
<%if Operation GT ""%><TD>Operation</TD><%endif%>
<%begindetail%>
<TR>
<%if ClientHost GT ""%><TD><%ClientHost%></TD><%endif%>
<%if LogTime GT ""%><TD><%LogTime%></TD><%endif%>
<%if ServerIP GT ""%><TD><%ServerIP%></TD><%endif%>
<%if BytesSent GT ""%><TD ALIGN=RIGHT><%BytesSent%></TD><%endif%>
<%if Operation GT ""%><TD><%Operation%></TD><%endif%>
</TR>
<%enddetail%>
</TABLE>
</BODY>
</HTML>
The world does not begin and end with Visual Basic. The Internet
is a big place, and several other client-side scripting languages
are competing for acceptance by Web programmers. The most prominent
rival is JavaScript, another client-side scripting language developed
by Netscape Communications Corporation. (Originally called LiveScript,
this scripting language really has nothing to do with Sun's Java
language, except that Netscape licensed the name JavaScript from
Sun.)
NOTE |
Many interesting JavaScript applications and their corresponding source code can be found at http://www.gamelan.com/.
|
In addition to JavaScript, we can expect other languages to be
adapted to work within Internet Explorer-most notably Perl, the
most popular CGI scripting language, and Python, another popular
language.
In general, Microsoft and other vendors will do well to support
a wide range of scripting languages. Microsoft, naturally, will
support VBScript with the most enthusiasm, but having a choice
is always more pleasant for the developer.
The ActiveX Control Pad is a significant HTML authoring tool from
Microsoft. With Control Pad, it's easier to develop Web pages
that incorporate either VBScript elements or ActiveX controls.
The Control Pad requires Windows 95 or NT 4.0 (beta 2 or greater),
as well as Internet Explorer 3.0. Control Pad can be downloaded
from
http://www.microsoft.com/intdev/author/cpad
If you are familiar with Visual Basic's form editor, using Control
Pad will be a similarly pleasant experience. Once Control Pad
is started, a window appears containing an editor where the HTML
is written. The editor also allows you to open or copy from an
existing Control Pad/HTML-written document, or one created with
any other HTML editor. Figure 2.16 is a shot of the editor when
you open a new document:
Figure 2.16: Control Pad Editor.
The controls are added to the page by choosing Insert ActiveX
Control from the Edit menu. Once you choose the control, you can
edit the properties of the control in the Properties response
window that appears. This response window contains the usual suspects
from a Visual Basic Properties window, as shown in Figure 2.17.
Figure 2.17: Control Pad Properties Window.
One reason why Control Pad will become popular is its relative
ease of use. For example, it comes with a large variety of controls
and their accompanying CSLID identifiers. When you insert, for
example, the Command Button control, the following is added to
the HTML document:
<OBJECT ID="CommandButton1" WIDTH=96 HEIGHT=32
CLASSID="CLSID:D7Ø5324Ø-CE69-11CD-A777-ØØDDØ1143C57">
<PARAM NAME="Size" VALUE="254Ø;846">
<PARAM NAME="FontCharSet" VALUE="Ø">
<PARAM NAME="FontPitchAndFamily" VALUE="2">
<PARAM NAME="ParagraphAlign" VALUE="3">
<PARAM NAME="FontWeight" VALUE="Ø">
As will be discussed in Chapter 3 a GUID is a unique 128-bit
identifier that each control must have. Control Pad automatically
inserts the GUID, so you don't have to worry about making a typographical
error entering the long string associated with each control.
Once the control is dropped into the editor, the file can be saved
and then opened in Microsoft Explorer 3.0. Our sample Command
Button page will look like Figure 2.18.
Figure 2.18: Internet Explorer Displaying Command Button.
You can press the Command Button, but nothing will happen. The
next thing you have to do is activate the control by adding code
to it. VBScript or JavaScript can be used. Control Pad comes with
a Script Wizard that helps simplify scripting, as shown in Figure
2.19.
Figure 2.19: Control Pad's Script Wizard.
On the left side of the scripting tool, you choose which event
you want to program. For coding our Command Button, you would
click on the words Command_Button_1 on the left side of the screen
to view the full selection of events that can be programmed. Typically,
you would program the Command Button to do something when the
user clicks the button. In the example below, we have programmed
the click event to Navigate to a home page when the button is
selected.
<HTML>
<HEAD>
<TITLE>New Page</TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="VBScript">
<!--
Sub CommandButton1_Click()
Window.location.href = "http://127.Ø.Ø.1/"
end sub
-->
</SCRIPT>
<OBJECT ID="CommandButton1" WIDTH=96 HEIGHT=32
CLASSID="CLSID:D7Ø5324Ø-CE69-11CD-A777-ØØDDØ1143C57">
<PARAM NAME="Caption" VALUE="HomePage">
<PARAM NAME="Size" VALUE="254Ø;846">
<PARAM NAME="FontCharSet" VALUE="Ø">
<PARAM NAME="FontPitchAndFamily" VALUE="2">
<PARAM NAME="ParagraphAlign" VALUE="3">
</OBJECT>
</BODY>
</HTML>
In addition to adding ActiveX controls to HTML documents, Control
Pad also lets you insert an HTML Layout Control into Web pages.
HTML Layout Control is an ActiveX control that Microsoft has developed
jointly with the Worldwide Web Consortium (W3C) to create a 2-D
environment with carefully placed controls. For more information,
see the W3C Technical Report, "Frame-Based Layout via Style
Sheets," at
http://www.w3.org/pub/WWW/TR/WD-layout.html
What the HTML Layout Control does is fine-tune the placement of
the controls you have put on your page. You can position your
controls to exact x-, y- and z-coordinates-even for overlapping
images. You can even add scrollable frame sets to your page instead
of just having the one main scrolling window.
The HTML author using this control has a tremendous amount of
freedom to implement interesting Web pages incorporating an ever-growing
family of controls that are viewed consistently, regardless of
the viewer. This is quite an accomplishment. Usually, the client's
viewer positions the control; but with Layout Control, the page
author can present the page in exactly the same layout, no matter
which viewer will be used.
The Layout Control is inserted into the HTML by Control Pad much
the same way as other ActiveX controls. The Edit menu contains
a separate item called Insert HTML Layout. After inserting the
layout, the editing window contains the following code:
<HTML>
<HEAD>
<TITLE>New Page</TITLE>
</HEAD>
<BODY>
<OBJECT CLASSID="CLSID:812AE312-8B8E-11CF-93C8-ØØAAØØCØ8FDF"
ID="testing" STYLE="LEFT:Ø;TOP:Ø">
<PARAM NAME="ALXPATH" REF VALUE="file:C:\Program Files\ActiveX Control Pad\testing.alx">
</OBJECT>
</BODY>
</HTML>
As you can see, the Layout object is inserted with its unique
CLASSID, and the object has a parameter that points to a file
named testing.alx. Figure 2.20 shows testing.alx as it is being
edited by adding various controls from the toolbox.
Figure 2.20: The Testing.Alx File As A Work-In-Progress.
<DIV STYLE="LAYOUT:FIXED;WIDTH:24Øpt;HEIGHT:18Øpt;">
<OBJECT ID="CommandButton1"
CLASSID="CLSID:D7Ø5324Ø-CE69-11CD-A777-ØØDDØ 1143C57"
STYLE="TOP:25pt;LEFT:25pt;WIDTH:72pt;HEIGHT:24pt;TABINDEX:Ø;ZINDEX:Ø;">
<PARAM NAME="Caption" VALUE="Oona's choice">
<PARAM NAME="Size" VALUE="254Ø;847">
<PARAM NAME="FontCharSet" VALUE="Ø">
<PARAM NAME="FontPitchAndFamily" VALUE="2">
<PARAM NAME="ParagraphAlign" VALUE="3">
<PARAM NAME="FontWeight" VALUE="Ø">
</OBJECT>
<OBJECT ID="TextBox1"
CLASSID="CLSID:8BD21D1Ø-EC42-11CE-9EØD-ØØAAØØ6ØØ2F3"
STYLE="TOP:25pt;LEFT:116pt;WIDTH:1Ø7pt;HEIGHT:25pt;TABINDEX:1;ZINDEX:1;">
<PARAM NAME="VariousPropertyBits" VALUE="7466Ø4571">
<PARAM NAME="Size" VALUE="3783;873">
<PARAM NAME="FontCharSet" VALUE="Ø">
<PARAM NAME="FontPitchAndFamily" VALUE="2">
<PARAM NAME="FontWeight" VALUE="Ø">
</OBJECT>
<OBJECT ID="Label1"
CLASSID="CLSID:978C9E23-D4BØ-11CE-BF2D-ØØAAØØ3F4ØDØ"
STYLE="TOP:83pt;LEFT:33pt;WIDTH:72pt;HEIGHT:18pt;ZINDEX:2;">
<PARAM NAME="Caption" VALUE="Label1">
<PARAM NAME="Size" VALUE="254Ø;635">
<PARAM NAME="FontCharSet" VALUE="Ø">
<PARAM NAME="FontPitchAndFamily" VALUE="2">
<PARAM NAME="FontWeight" VALUE="Ø">
</OBJECT>
</DIV>
Recall that the HTML file references the .alx file by the URL
parameter with the VALUE
file:C:\Program Files\ActiveX Control Pad\testing.alx
This .alx file defines the exact position of the controls.
Position is defined by the STYLE values. Look at the following
lines of code for the two controls that align in Figure 2.20:
STYLE="TOP:25pt;LEFT:25pt;WIDTH:72pt;HEIGHT:24pt
STYLE="TOP:25pt;LEFT:116pt;WIDTH:1Ø7pt;HEIGHT:25pt
Notice that the TOP value for both controls is 25pt. This means
that each of the controls is 25 points (72 points to an inch)
from the top of the window, and will always be aligned regardless
of the viewer used.
Even for the single task of inserting an object into an HTML document,
the Control Pad is surprisingly useful. Throw in everything else,
and it becomes a truly essential tool. We look forward to Microsoft's
future enhancements of this application.
The concept of the "style sheet" or the "style
file" is almost as old as publishing. We are all familiar
with what is sometimes called the "look and feel" of
a certain company's printed advertising; certain publications
can be identified just by a sample page from a typical issue.
Once a company settles on a distinctive character, it develops
a style to be followed by its typesetting departments whenever
anything is produced for that company. To make this style portable
from document to document, style files are created.
On large mainframe word processing systems, a style file comprises
detailed information on fonts and their characteristics, on the
amount of space between lines in a paragraph (called leading),
on the size of paragraph indents, and on just about any and all
attributes possible in a typeset document. This style file is
then called by the word processing system when the typeset document
is saved, and the proper style attributes are then applied to
the text.
Most desktop publishing systems, as well, use the concept of a
style file or template to store information on the appearance
of a document. Some of the better desktop publishing systems-FrameMaker,
for example-have very detailed and flexible layout capabilities.
One major difference in the newer desktop systems is the fact
that they are almost always WYSIWYG.
As more corporations begin to use the Internet as part of their
marketing strategy, the same concerns about paper products are
there for electronic documents. Companies want to retain their
particular "image" in the electronic Web documents that
bear the corporate name. And individual users, as well, are growing
in sophistication and wants to show ingenuity and creativity in
their Web pages. Everyone wants a particular style to call their
own.
Enter Microsoft's cascading style sheets (CSS). Based on
the philosophy of mainframe style files, along with the existing
Microsoft model of templates and the W3C Working Draft on this
concept, CSS contain most everything that goes into a "real"
style file.
Microsoft's style sheets are flexible; they allow three classes
of style sheets that are called "cascading" because
each class cascades over the next. The notion of cascading style
sheets is developed in great detail in the related W3C work-in-progress,
available at
http://www.w3.org/pub/WWW/TR/WD-css1.html
Consider the average Web page. For each page, there are the page
author, the reader of the page, and the reader's browser used
to view the page. Let's say that the author wants the words golden
arches to show up in 14pt Times Roman bold letters in a familiar
shade of yellow. Let's also assume that in some future release
of the CSS technology, readers will be able to create their own
style sheets for reading pages. So our reader has a thing for
the color green, and has set his style sheet to read all 14pt
Times Roman bold letters as green letters. And finally, let's
assume that the reader's browser has dark blue set for the default
color of the type. What color will be shown when our reader calls
up that page? The choices would seem to be yellow, green, or dark
blue, and the general rule is that the author's choice of color
would be the first priority.
If the author hadn't cared about the color, but the reader had,
then the reader's green would supersede the browser's dark blue.
And had neither the author nor the reader set the text color,
the browser's dark blue would appear. There is an exception to
this rule, called the "important" rule. If the reader
had inserted the following code into a style file, it could not
be changed by the author's color choice:
P { color: black ! important }
This exception to the rule is especially useful for readers who
have trouble with small type, or any size type in a particular
color.
NOTE |
As mentioned earlier, Internet Explorer currently does not support the reader-defined page, but it is planned for future releases.
|
There are three implementations of "styles": linking,
embedding, and inline.
The author can choose to link to a style sheet held in
a separate file. This is the model that would be used to achieve
consistent-looking documents throughout a group of Web pages.
Embedding a style sheet into an HTML file is the best option
for the person who wants to experiment with different looks for
each of their Web pages. This style is set on a page-by-page basis,
so the author can reuse the instructions on several pages, but
not necessarily on all pages.
The author can add an inline style to a particular tag
set in the HTML file if the need arises for, say, indenting just
one line differently from the others around it; or if, for emphasis,
a word is to appear in a brighter color in an otherwise black-and-white
document, for shock value or to make a point.
Linking to an external style sheet is accomplished by including
the following code in the Web page, between the <HEAD> and
</HEAD> tags:
<LINK REL=STYLESHEET HREF="http://www.your.com/yourstyle.css" TYPE="text/css">
Note that there is no ending </LINK> tag required. The author
must create a file with a .CSS filename extension, containing
the style data.
To embed a style, you must nest the information in between the
<STYLE> and </STYLE> tags, which have to be nested
in between the <HTML> and the <BODY> tags at the beginning
of the page. Here is an example of embedding a style into an HTML
document:
<HTML>
<STYLE TYPE="text/css">
<!--
BODY {font: 1Øpt/12pt "Times"};
H1 {font: 12pt/14pt "Times";
font-weight: bold;
color: black}
H2 {font: 1Øpt/12pt "Times";
font-weight: normal;
font-style: italic;
color: black}
P {font: 1Øpt/12pt "Times";
font-weight: normal;
color: black}
-->
</STYLE>
<BODY>
.
.
.
</BODY>
</HTML>
Notice that the <STYLE> tags are nested within comment tags.
This is necessary because some browsers do not support the <STYLE>
tag; they read everything after the tag as text that ought to
be displayed in the page. Netscape does not currently support
the <STYLE> tag in their current release, but recognizes
that it should not print out the code in between the tags.
The author's third option is to create an inline style. Think
of it as the power to change your mind about your style sheet
because you want something to appear differently-either for a
single instance of a tag, or in an entire section of the document.
Let's say that for some reason you want to have one section of
the text appear in 32pt blanched almond, leaving the other parts
of the document just as they are. This would be accomplished with
the <SPAN> and </SPAN> tags.
<SPAN STYLE="font-size: 32pt; color: blanchedalmond">
<H1>
These are the words that must be in a different size and color!</H1>
<UL>
<LI>For emphasis
<LI>For example
</UL>
</SPAN>
Although the inline option may seem appealing, it should be avoided
if possible. One of the benefits of having a separate style file
is that your HTML pages will not be cluttered with a bunch of
style tags. Using inline style is actually a throwback to the
time before the existence of style files. The complaint then was
that it is more difficult for the author to keep track of what
is happening during editing and revisions. Creating the link to
a separate file is by far the preferred way of dealing with style
in HTML documents.
But what about our almond example above? How could a link style
have accomplished this "dramatic" effect? Well, the
style file has a notion of classes. Here is what one of the lines
in the .CSS file will look like:
H1.dramatic { font-size: 32pt;
color: burntalmond }
If this is done, then the code for our above example becomes:
<H1 Class=dramatic>
These are the words that must be in a different size and color!</H1>
<UL>
<LI>For emphasis
<LI>For example
</UL>
Cascading style sheets represent a whole new level of HTML sophistication
and complexity. Although Microsoft was not the first to incorporate
CSS in their Web browser, the company's support for CSS virtually
ensures widespread adoption in the near future. You can expect
a probable wave of fresh-looking Web sites developed with style
sheets.
Many options for managing HTML content are either available now
in the current version of Internet Explorer or will probably become
available in future releases. W3C's work-in-progress document
outlines several interesting alternatives that are being considered
for future releases of HTML. Once these possibilities are actualized,
Microsoft will probably incorporate them into its browser product.
As mentioned earlier in this book, we are dealing with-in almost
all cases-alpha or beta releases of software that are being changed,
upgraded, and tested as we go to press. Keep this in mind as you
join the software development process, by downloading, implementing,
and reporting bugs to the makers of the software.
Not long ago, "coding" an HTML page simply meant arranging
the static HTML elements that make up a Web page. The World Wide
Web is still in its infancy, though, and we can expect all sorts
of new tools and techniques to hit the ether in the future. Although
this makes the Web a richer environment for users, it also significantly
complicates your job of developing HTML content.
In this chapter we've given you a quick start to using a few of
the tools available for developing Web material for Microsoft's
Internet Explorer. Now you know what's possible with these tools-and
the gory details will no doubt become the subject of entire books
available to you in the near future.
- VBScript, a lightweight version of Microsoft's Visual Basic,
which offers the developer a means of embedding VB code in a Web
page. This client-side scripting opens up all sorts of possibilities
and advantages, compared to the traditional CGI alternative. By
shifting CGI tasks to client-side scripts, much of the back-and-forth
client request/server response interaction can be eliminated.
This makes your job easier because you need not create CGI server
scripts to handle every user message. Much of this can now be
accomplished in one place: the VBScript.
- The ActiveX Control Pad is a nifty tool for creating Web pages,
incorporating ActiveX controls and VBScript. The ability to drop
ActiveX controls into a document without having to look up the
GUID is worth the price of downloading this tool alone. We also
found the Script Wizard very handy. You can expect Control Pad
to be significantly enhanced over time, streamlining the process
of developing VBScript pages.
- Cascading Style Sheets will bring a whole new look to the
Web, adding a layer of elegance as well as giving both the HTML
designer and the Web user more control over the appearance of
a Web page. Without style sheets, you constantly have to consider
which HTML features are supported by a given browser. Designing
complex pages that will make sense when viewed with various browsers
is often a headache with no cure, but we can look for style sheets
to be the medicine.
The development of HTML content will continue to grow. Microsoft
doesn't invent everything, but they are indeed competitive and
like to stay on top. You won't want to miss checking out the Microsoft
Web pages on a regular basis. A good place to start is the Site
Builder Workshop at
http://www.microsoft.com/workshop/
It offers a comprehensive introduction to the various Microsoft
offerings.