Skip to main content.

Web Based Programming Tutorials

Homepage | Forum - Join the forum to discuss anything related to programming! | Programming Resources

Teach Yourself VBScript in 21 Days

Day 10 -- An Introduction to Objects and ActiveX Controls

DAY 10

An Introduction to Objects and ActiveX Controls


CONTENTS




Yesterday you looked at some of the intrinsic controls you can manipulate from your VBScript code. If you've been a Web page author for a while, you probably recognized the intrinsic control types; the check box, text box, radio button, and other controls have been supported in HTML all along. Traditionally, they collected input to pass back to the server, but with the advent of VBScript, you can control them directly. What if you want to offer some level of interaction not supported by those intrinsic controls? Some very powerful alternatives exist. The emerging HTML object extension opens the possibilities to incorporating virtually any object into your pages, and VBScript provides a means to control those objects. As a result, the possible ways to expand the bounds of your Web pages are virtually unlimited. However, one of the easiest, most powerful ways to extend those bounds is through a type of object introduced by Microsoft as part of their Internet strategy called ActiveX controls.

Using objects in general, and ActiveX controls in particular, is central to the art of VBScript programming if you plan to develop scripts of any level of sophistication. A clear view of these fundamental building blocks lays the foundation for more elegant and advanced programming. Today's lesson provides that view by first providing some overall background, context, and definition for what an object is. Then, you'll learn about the particulars of ActiveX controls. Many ActiveX controls exist, but today's lesson examines one particular control to highlight the approach for integrating an ActiveX control into your program. That control is the label control, one of the most commonly used ActiveX controls. Subsequent lessons then build on this starting point by introducing more ActiveX controls and the code necessary to create scripts that incorporate them.

Objects

You might find that you want to incorporate more visual pizzazz into your Web pages than you can by strictly using core HTML constructs. Perhaps you want to add some advanced multimedia capabilities to your Web page. The technology to support what you need to do exists if you could just graft it into your page. You might have a special programming function that you'd like to perform that is hard or impossible to program in VBScript. It might be available in some form of usable component that you can purchase from someone else, if only you could integrate it into your script. You just need to know how to add the relevant files and references to your page. The HTML element that enables you do this is the object. Objects let you incorporate components into your Web page. Generally speaking, if you incorporate a component into your page, you can incorporate it into your script as well.

Why Objects Are Needed

Over the last two days, you have looked at some ways to integrate added functionality into your pages and scripts with input controls. These are very similar to objects, but with a key difference: They are a native part of the HTML language. The browser/VBScript environment (under Microsoft Internet Explorer) inherently knows about them. The rules for handling these intrinsic controls are preprogrammed into the browser. You can reference intrinsic controls directly from your code as long as you have defined them with the <INPUT> tags discussed on previous days.

Objects, including the external ActiveX controls, are a slightly different beast. Consider the case of controls, which provide visual and programmatic extensions to your pages and scripts. Any developer with adequate knowledge can provide such a control. Because in theory you can have thousands of controls from thousands of providers, it is impossible for the browser to have support preprogrammed for all of them. These controls are packaged in separate files and defined to the operating system through systemwide classes. Some means is necessary to tell the browser and script the location, calling conventions, and characteristics for these components.

Object Definition

The HTML language provides the means to make the object definitions. At the time this book was published, the procedure for inserting objects was still in draft form but had gained widespread support. You can expect leading edge browsers to follow this model or a close derivative. To indicate to a browser that you want to insert an object, the first step in HTML source code starts, as you probably expect, with a tag. The tag to use to indicate an object is one that even makes perfect intuitive sense: <OBJECT>!

You might need to insert objects for a wide range of purposes other than what ActiveX controls fulfill. A Web page can consist of many types of elements, including images, controls, Java applets, video, audio, and embedded compound documents, as well as other new forms of media that might yet spring into existence. As the World Wide Web Consortium (W3C) assessed these needs, it realized that a hodgepodge of different approaches for incorporating different media, each with its own tag, was not ideal. Instead, a well-defined <OBJECT> methodology provides a general solution that you can use for all objects to be incorporated into a page. The discussion that follows pertains to incorporating any object into a Web page. The examples later today will look specifically at how an <OBJECT> definition is used with ActiveX controls. However, keep in mind that <OBJECT> provides the generic framework for integrating any type of object. Later, we will examine its use for other types of objects as well.

Note
The World Wide Web Consortium defines Web standards. If you want more information on the W3C working draft for "Inserting Objects into HTML," you can find it at http://www/w3.org/pub/WWW/TR/WD-object.html. You can find a list of W3C working drafts at http://www.w3.org/pub/WWW/TR.

Use of the <OBJECT> tag is best understood by looking at some simple examples. The label control is a good place to start. This control is one of a new generation of ActiveX controls that will be discussed shortly. For now, you just need to understand a couple of high-level details about this control to understand how it is treated as an object. The label control enables you to define, through appropriate statements in an object declaration, a string of text characters that can appear anywhere on a page. So far it sounds like a heading, but there are a few differences. One difference is that the label text can be positioned at an angle, so it can appear diagonally across a page. Another is that the label, like most objects, can be modified by a VBScript program even after a page has been initially generated. Figure 10.1 shows a page that uses a label control. The label is the diagonal text on the left of the page.

Figure 10.1 : A page with an object- the ActiveX lable control.

If you looked at the HTML source file for this page, you would see that the control is included by using the <OBJECT> tag. The <OBJECT> tag uses the relevant attributes and settings for the label control. Listing 10.1 shows the format for this object definition used to include the label control on the Web page.


Listing 10.1. The object declaration for an ActiveX label control.
<OBJECT
classid="clsid:99B42120-6EC7-11CF-A6C7-00AA00A47DD2"

    id=lblAd
    width=240
    height=240
    align=left
    hspace=5
    vspace=5
>
<param name="angle" value="45" >
<param name="alignment" value="2" >
<param name="BackStyle" value="0" >
<param name="caption" value="50% off studded trail running shoes!">
<param name="FontName" value="Arial">
<param name="FontSize" value="20">
<param name="FontBold" value="1">
<param name="FontItalic" value="1">
<param name="ForeColor" value="255">
</OBJECT>

Object Attributes

The object tag is similar to the standard HTML <BODY> tag format in many respects. It has both a start tag <OBJECT> and an end tag </OBJECT>. Within the start tag, you can define additional attributes that further describe characteristics common to all objects. In other words, all the lines shown in Listing 10.1 following the <OBJECT portion of the tag but preceding the next > are attributes. These attributes, which are specifically defined by the HTML draft standard for objects, describe standard object characteristics to the browser.

You can specify many different attributes for an object. Only some may be pertinent to any specific type of object. For example, the specific type of object defined in Listing 10.1 is an ActiveX control. That object's declaration uses attributes that pertain to an ActiveX control object. Table 10.1 summarizes the full list of attributes for all types of objects.

Table 10.1. Object tag attributes.

Tag
Description
ALIGN* Where the object should be placed-current text line, distinct unit, or aligned left, right, or center.
BORDER The width of the visible border around the object.
CLASSID* Class identifier or URL that identifies the implementation of an object.
CODEBASE* Additional URL to supplement the CLASSID URL. This can be used, for example, to locate the control on the network if it can't be located as already existing on the system from the CLASSID.
CODETYPE The Internet Media Type of the code that is referred to by the CLASSID attribute. This provides further information about the type of entity this is, such as an OLE Automation object. With ActiveX controls, the CLASSID itself is sufficient for the browser to verify the type of entity, and CODETYPE is not required.
DATA URL that indicates an object's data, such as the GIF file for an image object.
DECLARE Indicates the object should be declared but not instantiated.
HEIGHT* The height of the object picture.
HSPACE* The horizontal margin around the object picture.
ID* Defines a documentwide identifier.
ISMAP Signifies that the object is defined within a hypertext link, and static image mouse clicks should be sent to the server.
NAME When DECLARE is not in effect, this tag signifies that the object's NAME attribute and associated data should be sent to the server along with other form fields in response to the submit process.
SHAPES Signifies that the object contains anchors with shape-associated hypertext links.
STANDBY A short text string the browser can show while loading the data and object implementation.
TYPE The Internet Media Type for the data that is referred to by the DATA attribute.
USEMAP The URL for a client-size static image imagemap.
VSPACE* The vertical margin around the object picture.
WIDTH* The width of the object picture.
* The attributes that apply most directly to ActiveX controls.

Table 10.1 presents all the object attributes that are part of the current draft standard so that you can appreciate the full range of object declaration capabilities. As shown in the example in Listing 10.1, you will probably only use a subset of these attributes when you define ActiveX controls. The following sections describe in greater detail the key attributes that apply most directly to ActiveX controls.

The Object's CLASSID Attribute

The CLASSID is an essential part of any ActiveX object declaration. It identifies the implementation of an object to the browser. In other words, it provides the browser with a path to the code behind an object. It describes what kind of class an object belongs to and thereby identifies the code that defines its behavior. The CLASSID indicates, for example, whether this is a label object that should look and behave like a label or a graph object that should look and behave like a graph. The information supplied for CLASSID with the current Internet Explorer 3.0 implementation consists of class registration information contained in the system registration database. The browser uses this to locate the relevant file on the system.

This class registration information consists of a cryptic-looking string of digits that corresponds to information in the registration database. The registration database, in turn, knows the location of the library file (with an OCX extension in Windows) that provides the code for this class. In later versions of the Internet Explorer, this will probably evolve to a more easily understood program ID (for example, ="PROGID:Internet.Label.1") rather than the corresponding number reference in the previous example (clsid:99B42120-6EC7-11CF-A6C7-00AA00A47DD2).

Another characteristic of CLASSID in the very early beta versions of Internet Explorer was that the CLASSID was enclosed within curly brackets. This syntax, however, did not conform with the draft standard for objects. As a result, later versions of the Internet Explorer eliminated support for a CLASSID definition that used curly brackets. This is pointed out just in case you ever come across a page written for the early beta-level browser. The current-level Internet Explorer will give you warning messages when you're loading the page if object definitions with the old syntax are encountered.

According to the object attribute specification, you can also identify the base location of an object in terms of a URL (uniform resource locater) through the CODEBASE attribute. This means an object can potentially be specified as a file available on the Web. This opens the door to some of the most exciting possibilities with using object components. You can access and download controls across the Web with pages that use them.

If a control doesn't exist on your system (which the browser verifies using CLASSID), the CODEBASE URL is used, if present, to retrieve the component from wherever it resides. In the early beta versions of Internet Explorer, you had to provide ActiveX access for your system by downloading and installing a specific ActiveX control kit. With the current version of Internet Explorer, CODEBASE is fully implemented and controls can be downloaded across the Internet by the pages that require them. If you don't have a control that a page uses and CODEBASE points to Microsoft's Web repository, for example, the control is automatically downloaded. The browser does provide you with a dialog to notify you and give you the option to suppress the download, depending on the security option settings of the browser.

It is a good assumption that later distributions of the browser will directly install at least some of the Microsoft-supplied ActiveX controls along with the browser when you install the browser on a system. Ultimately, an Internet model of ActiveX distribution will probably evolve based on the URL attributes of an object. Today's lesson focuses on controls rather than issues of component distribution and assumes the controls are already available on your system and registered in your system registry. Control distribution issues are addressed in more detail on Day 19, "Dynamic Page Flow and Server Submittal."

Note
The ActiveX control kit was available for download at the time this was written from www.microsoft.com/intdev. Search for ActiveX control. You should ensure the ActiveX controls are available on your system in order to use the examples that appear throughout this book. Not all the samples make use of the CODEBASE property, so the automatic retrieval won't take place in every case. If you have the controls downloaded ahead of time (whether through an explicit download or perhaps through installing later versions of Internet Explorer), you'll be all set. You can also select the Requirements option on page Default.htm on the CD-ROM to automatically download the required components for this book.

The Object's ID Attribute

The ID of an object defines the identifier of the element. This is the name that you must use to refer to this specific instance of the object anytime it is referenced within the page. Why would you need to refer to an object? The most likely place is within your VBScript code itself. If your code interacts with the object at all, you need a name to use when you refer to that object. Suppose you wrote a program that changed the color of a label when a user clicked a button. The name you would use in the code statement that manipulates the label control is the name that is specified by the ID attribute. An ID attribute must start with a letter and can be followed by letters, digits, and - (hyphen) and . (period) characters. (Note, however, that although you can define an ID to contain a . and - in the object declaration, you will run into problems if you attempt to reference a name with these characters from your VBScript code. For that reason, you can consider the set of legal characters for the ID for practical purposes to be letters and digits.) LblAd is the ID of the control used in the object declaration in Listing 10.1.

The Object's WIDTH and HEIGHT Attributes

The WIDTH and HEIGHT attributes together specify the size of the object when it is drawn on the Web page. If an object area's true dimensions differ from those indicated by WIDTH and HEIGHT, the visible picture for the object will be stretched to match the specified size. Some browsers use this information for additional purposes. The Internet Explorer, for example, also uses these dimensions to draw an appropriately sized placeholder for the object's picture representation as the object is being loaded. These attributes are specified in pixels by default but can also be described in terms of screen percentage, such as

height=50%

In Listing 10.1, the width of the area containing the label is constrained by the <OBJECT> attributes to be 240¥240 pixels. If caption text was supplied for the label in a font size that did not fit within this area, that text would be truncated to fit.

The Object's ALIGN Attribute

The ALIGN attribute designates where to position the object. Based on the current draft standard, the ALIGN attribute can take any of the following values:

Value
Description
BASELINE The object's bottom is vertically aligned with the current font's bottom.
CENTER The object appears centered between the left and right margins.
LEFT The object appears down the current left margin.
MIDDLE The object's middle is vertically aligned with font's baseline.
RIGHT The object appears down the current right margin.
TEXTMIDDLE The object's middle is vertically aligned halfway between the baseline and the current font height.
TEXTBOTTOM The object's bottom is vertically aligned with the current font's bottom.
TEXTTOP The object's top is vertically aligned with the current font's top.

The Object's VSPACE and HSPACE Attributes

The VSPACE and HSPACE attributes combine to designate the margins for the object's picture representation. VSPACE indicates the vertical margins, and HSPACE indicates the horizontal margins. An HSPACE of 5 and a VSPACE of 5, for example, would indicate that the browser should provide a margin of 5 pixels around the object picture. These attributes are specified in pixels by default but can also be described in terms of screen percentage, such as

HSpace=2%

Syntax for Specifying an Attribute

Now that you have a feel for what attributes are, you should keep in mind the syntax that you can and cannot use when specifying them. The label example shown in Listing 10.1 references attribute values without any quotation marks:

id = Label1

If you've studied the source code for many Web pages, you might notice that some pages reference attribute values with quotation marks:

id = "Label1"

Either of these approaches is legal. You can omit the quotation marks if an attribute value consists only of the characters a to z, A to Z, 0 to 9, the hyphen, and the period. Another rule will probably cheer Windows users and sadden UNIX diehards. Attributes are entirely case insensitive. That means that

id = Label1

is the same as

id = LABEL1

to any browser-at least, any browser that adheres to the standards!

Visual Representation of Objects

As mentioned earlier, you will need only some of the many legal object attributes when defining an ActiveX control-specifically, the CLASSID, ID, WIDTH, HEIGHT, ALIGN, HSPACE, and VSPACE attributes. Notice that four of these attributes pertain to the way an object is rendered on the page. The majority of controls have a visible representation that appears on the page. For example, the label control displays text to the user and is clearly visible on the page. However, some controls do not show up on the page but simply perform a task at the request of code with no visible representation of the control for the user to see.

A timer control falls in this category. Code you write can use this control for timing purposes, but the user of your Web page doesn't see a visible sign of the timer control except through whatever interface your program presents. For an object such as this control, even the WIDTH, HEIGHT, HSPACE, and VSPACE attributes are not relevant. Therefore, they do not need to be specified. This will be illustrated more fully in the ActiveX control examples that you see over the next two days.

Note
Many programming environments for software that run under graphical operating systems now provide sophisticated visual tools to incorporate components into programs. Often, you can just drag and drop a component icon onto a program interface to add the component to your program. Fortunately, at the time of this writing, such tools are starting to appear in some forms. Microsoft has an ActiveX control insertion utility that moves object tag text for a control to the clipboard for easy text insertion. Microsoft's ActiveX Control Pad editor (discussed in detail on Day 18, "Advanced User Interface and Browser Object Techniques") has a built-in capability to do the same type of insertions and represents controls visually in the left margin of the editor. Both of these tools are currently free on the Microsoft Web site (under www.microsoft.com/intdev). More tools will likely evolve as well. Short of having a snazzy tool, the only way to add objects is to insert the lines of code of the object declaration right into your source file. Tools will evolve with time, and the state of the art seems to change from month to month. Check online resources and industry periodicals to find out the current state of the art when you read this. You can also refer to the book's tips and pointers page on the Web documented in Appendix B, "Information Resources," which lists some late-breaking findings.

Object Parameters

If you've used HTML to build Web pages, the attributes of the object tag are probably somewhat familiar to you. The attributes are common to other tags such as <BODY> and <IMG> as well as <OBJECT>. Another aspect of the object tag that is unique to it, however, is the <PARAM> tag. <PARAM> specifies object parameters within an object definition. An object parameter is a characteristic of an object that is defined by the object itself, rather than the HTML standards. If you have experience with Visual Basic or an object-oriented programming language, you can picture a parameter as a property of the object. For that reason, <PARAM> parameters are often referred to interchangeably as properties or parameters, and you will find the property terminology used throughout the rest of this book. The <PARAM> list of an object is essentially its property sheet. It defines a list of property characteristics and the initial settings for those characteristics. The properties provided and the way these properties are utilized by an object is object dependent. In the case of ActiveX controls, it depends completely on the way the control was written. Typically, the properties of a control are well documented and describe the way in which various property settings affect the appearance or behavior of the control.

<PARAM> is therefore a tag that is a part of an object definition; it is embedded between the <OBJECT> and </OBJECT> tags. <PARAM> requires no ending tag and carries with it just two main attributes: NAME and VALUE. NAME is used to designate the name of a property, and VALUE determines its initial value. If you refer to Listing 10.1, you can see that the label ActiveX control object definition defines a font name property:

<param name="FontName" value="Arial">

Tip
An object's <PARAM> tags perform essentially the same function as do properties within Visual Basic 4.0.

The FontName property is a property of the label control that determines the font used to display the label's caption. The FontName property is specified a parameter rather than an attribute in the object definition because it is object specific rather than generic to all objects. Odds are that many objects will have no use for such a property; an image or audio file doesn't need a font specification, for example. In general, think of object attributes as standard instructions to the browser on how to deal with a generic object. Object parameters are object-specific properties that deal with characteristics unique to that object or similar objects.

You first assign object properties when authoring a page to create the initial state of an object. You also will probably reference many properties in your scripts to control the behavior and characteristics of an object. You can reference a specific property in your code by designating the ID of the object, a period to indicate that what follows is a property, and then the specific property. For example, to print a message box containing the caption property of the label object (which is defined in Listing 10.1), you would use the following statement:

msgbox lblAd.Caption

When you reference the name of the object and property in a statement, the corresponding value is returned. When the object and property indicator appear on the left side of an assignment statement, such as

lblAd.Caption = "Sales Off"

the object's property value changes to the new value indicated in the assignment. This capability to set and retrieve the value of object properties provides a powerful means to interact with controls within your scripts. You can write code to inspect and control any aspect of the controls you incorporate in your programs.

ActiveX Technology

ActiveX is a technology standard that was introduced by Microsoft in March 1996. It defines a standard approach for implementing controls that can be easily integrated into applications, including Web pages. ActiveX grew out of the very successful Visual Basic-related component technologies and strategies that preceded it. These included controls called VBXs, which were used by the early versions of Visual Basic, and controls called OCXs, used by Visual Basic 4.0 and most other Windows programming languages. OCXs provided component integration based on Microsoft's OLE (object linking and embedding) technology. OLE is a sophisticated, complex family of standards, which in a general sense deal with communication between applications, registration, and storage issues.

VBXs and OCXs provided the capability to quickly and easily expand the function of a program to Visual Basic and other rapid application development languages. You simply had to insert a component into your program to add function, and then you could programmatically drive that component to perform work. As a result, you could easily expand the power of your programs by taking advantage of communication and control with what were essentially code libraries provided by other companies. If you wanted to add a calendar to your program, you could simply add a calendar control you purchased from a third-party provider, and-presto!-you had a fully programmable calendar with a complete user interface built into your program.

This is a powerful programming model. It was a natural to apply it to Web page programming with the maturation of scripting languages such as VBScript. There was only one problem. The steady evolution of controls in the Windows environment was at a state where the technology was rather bloated and platform specific. OCX controls carried with them the considerable overhead involved in communicating according to the OLE protocols. OLE support was not available in many other environments. A good Internet-targeted control needed the potential for downloading across the network to accompany a Web page that used it. That would require small controls with a light footprint. Likewise, you'd need controls that could efficiently operate in a variety of operating environments to craft a page that could be used anywhere.

Microsoft provided further control standard guidelines that encompassed the old OCX technologies as well as went beyond it. This technology was named ActiveX, as part of a broader ActiveX strategy to revolutionize many aspects of Windows for the Internet era ahead. It is important to realize that traditional OCX controls are now ActiveX controls under the umbrella of the new ActiveX control term. This terminology does reflect a powerful capability, for it means that you have literally thousands of controls you could potentially incorporate into your Web pages.

Actually, the ActiveX controls are just one part of a broader ActiveX technology strategy. This technology centers on the concept of treating applications as well as traditional Web pages as active documents hosted in an all-encompassing shell. The shell becomes the next generation browser that can essentially host all interactions with the computer. The core of the strategy then, at least on the Windows environment, is that the operating system and browser become one. Web pages, as well as everything else, become "active." The browser user of the future will be able to shift from applications to Web pages without detecting much difference between documents and applications rather than interact with the traditional static Web page content of the recent past. In this new vision, everything-document and application-has full-scale active capabilities. The label control discussed today makes use of this ActiveX technology. They provide a means to make pages active. These controls enable you to incorporate client-side smarts into Web pages. ActiveX controls are just one type of object that you can insert into a Web page. They are also one of the most common types of objects that you will handle in your scripts because the controls provide one of the easiest ways to extend the power and function of your programs.

ActiveX Control Overview

ActiveX controls come from three main areas of origination. The first is Microsoft itself. Microsoft has provided many free-of-charge ActiveX controls already, and you can expect more to be available to help foster growth of their Internet and operating system environments. The second source of controls is third-party vendors. Many companies will produce ActiveX controls that can perform specific tasks and sell these controls through various avenues. It is typically cheaper to purchase a control than to expend the labor to write the same code yourself, so a steady market for controls exists.

The third source for controls is you (or your company) yourself. Why would you write an ActiveX control? Suppose you want to integrate some type of functionality into your program but cannot locate a control on the market that serves the purpose. The prospect of writing it yourself so that you can write the control once and then use it from many different VBScript programs might start to sound appealing. You can write ActiveX controls in a variety of languages that are not as restricted as VBScript. ActiveX controls also often can offer significant performance advantages. They also provide a very good package for reusable code if you want to share some functions with many different scripts. For all these reasons, many developers will probably produce their own ActiveX controls at times, as well as use those provided by Microsoft and third-party vendors.

One of the reasons that considerable discussion is focused here on ActiveX controls is that much of your ability to use VBScript to produce impressive, active Web pages will depend directly on your ability to incorporate these controls. VBScript is to a large extent the glue that holds your program together. By using this glue, you can quickly incorporate components according to your needs and build a powerful application engine.

It is important to be clear on some fundamentals of using controls to employ them effectively. These fundamentals include the use of control properties, methods, and events. The same property/method/event model that applies to the intrinsic controls discussed on Day 8, "Intrinsic HTML Form Controls," and Day 9, "More Intrinsic HTML Form Controls," applies to ActiveX controls as well. The primary difference is that intrinsic HTML controls have a more limited number of events, properties, and methods than do most ActiveX controls declared through object declarations. You set and get control-related characteristic values through assignment statements, referencing control properties by referring to the object and designating the relevant property after a period (.).

When you define properties within the <OBJECT> tag, you are supplying startup values for that object to use. If you choose not to define a particular property because you don't feel you will need to reference it, you can simply leave it off the <PARAM> list. The control will use its own defaults for any properties not supplied.

The following sample line of code shows a VBScript statement that changes the value of the label control caption property. The name of the control, lblAd, was designated when the object was declared earlier in the HTML source through the <OBJECT id="lblAd" > attribute. Caption was designated as a property within this object declaration by the <PARAM NAME="Caption"> parameter. This example assigns a new string to the caption property of the label object. This statement could appear within any block of script code; for example, it could execute in response to a button click. As soon as the script code containing this statement finishes, the new caption is displayed for the label:

lblAd.caption = "This is a new caption!"

Note
If you're familiar with Visual Basic 4.0 or VBA, you might be accustomed to using the with statement to refer to properties. This statement is not supported in VBScript.

In addition to manipulating object properties, you can also use object methods in your code. When you use an object's method, you are essentially calling prepackaged function or subroutine calls from the object. In the following example, the lblAd control's AboutBox method is called to display an AboutBox associated with that control. The AboutBox method is an intrinsically defined method or function built into the control. You do not have to explicitly define such methods in your Web page <OBJECT> declaration. You get access to all the methods of an object simply by including the <OBJECT> tag:

' Show the about box for this control
lblAd.AboutBox

As you can see, you can weave a lot of programming around controls. You can set properties of ActiveX controls and call methods that trigger code performed in the control. You've covered all the bases except one. What if the user interacts with the control on the Web page, or the control reaches a certain state you want your code to react to? How can you write code that reacts in such a situation? These types of situations are called events. ActiveX controls provide the same solution for handling events that you saw covered on previous days in the discussion of intrinsic controls. Events are predefined conditions of the control with which you can associate code. When the condition occurs in the control, your code is triggered.

Consider again the label control. A predefined event for the label control is the Click event. If the user clicks a label, the control's Click event handler subroutine is performed, if the script has one defined. The block of code in Listing 10.2 is the event-handling code for the Click event of the label shown in Figure 10.1.


Listing 10.2. The Click event for the label control.
<SCRIPT LANGUAGE="VBSCRIPT">
<!--
   sub lblAd_Click
        msgbox "Our studded trail shoes are especially well-suited " & _
               " for running over glaciers or through muck-covered " & _
               " streams with nary a slip!",0,"A Steal at $49.00!"
   end sub
-->
</SCRIPT>

It is the name of the lblAd_Click subroutine that associates this code with the label's Click event. The first part of the subroutine name, lblAd, associates it with the ID of the ActiveX control object. The underscore (_) is the notation that indicates an event definition may follow. Then, because the Click that follows is the name of a predefined label event, the code in subroutine lblAd_Click will be performed whenever that specific label is clicked. You can see the result in Figure 10.2. Whenever the user clicks the label advertising the 50 percent off sale, the message box shown in the figure pops up to provide more details to the user.

Figure 10.2 : A message box is displayed in response to clicking the label.

VBScript provides another alternative method for defining event procedures as well. You can explicitly define an event procedure for a block of script code through the script tag. You simply specify the event that the script code is to handle in the tag through the EVENT parameter and indicate the ID of the control the event code is associated with through the FOR parameter. The example in Listing 10.3 performs exactly the same event handling as the example shown in Listing 10.2. If you use this approach, the event handling code is specified in the main code in the script rather than within a procedure. A script associated with an explicit event only gets executed when the event occurs.


Listing 10.3. Another way to define the Click event for the label control.
<SCRIPT LANGUAGE="VBSCRIPT" EVENT="Click" FOR="lblAd">
<--
     msgbox "Our studded trail shoes are especially well-suited " & _
               " for running over glaciers or through muck-covered " & _
               " streams with nary a slip!",0,"A Steal at $49.00!"
-->
</SCRIPT>

A natural question arises if you're thinking about controls for the first time. How do you know which properties, methods, and events you can use for any given control? You might wish you could add your own properties to the label control, extending its functions in the ways you want. Maybe you can think of some really nice code you could write if only a control supported a certain type of event. Wishing won't do you any good, however. Because you're using prepackaged code by using the control, the properties, methods, and events are already defined. It's a strictly defined set. You can only reference properties in your code or <PARAM> tags if they have been supported within the designated control. Likewise, you can't call methods unless they are supported within the control. The only event code that ever will get triggered is code for the events that the control directly supports.

Note
You can always write your own ActiveX control if you can't find one that meets your needs. Writing an ActiveX control is not a task for beginners. On the other hand, you don't have to be a guru to tackle the task either, as long as you know a language such as C++ that supports creation of ActiveX controls. The next version of Visual Basic Enterprise Edition will probably let you create controls from the Visual Basic language, making the task approachable for many more programmers.

Your choice of control interaction is clearly defined by the control. When you incorporate a control, one of your first tasks should be to round up the documentation for it, whether it's online or on the Net. Thoroughly read up on all the supported properties, methods, and events. This will serve as your guide for incorporating that control into your scripts and writing code around it. You can't read the control developer's mind to understand what he was thinking when he constructed the control. You could perhaps determine how a control behaves through lengthy experimentation. Good documentation provides a much faster path, however. In that respect, well-documented controls with plenty of examples of how their properties and methods should be used are a very important part of component integration.

Now with the definition of objects and ActiveX controls in perspective, you can began to put specific ActiveX controls to work. The rest of the day, I'll focus further on the label control. This control is one of the simpler, yet most frequently used, controls. Once you follow the examples of integrating the label control into VBScript, you will have mastered one of the fundamental skills of creating active Web pages-incorporating objects to make your pages more powerful.

Some of the other core ActiveX controls provided by Microsoft to extend the function of your Web pages and scripts will be illustrated in the pages ahead. Day 11, "More ActiveX Controls," will cover some more control usage in detail; examples with the new item control and the timer control will illustrate these points. Other controls will be used in samples throughout the upcoming days. Bear in mind that although the controls you will see are some of the most commonly used controls, many other ActiveX controls are also available to extend the function of your scripts in other ways. Table 10.2 lists the Microsoft ActiveX controls covered.

Table 10.2. The Microsoft ActiveX controls examples in this book.

Control
Description
Lesson
LabelDisplays a label on a page Day 10
New ItemDisplays a new item indicator until a given date Day 11
TimerUsed for timing events Day 11
ChartProduces a variety of charts Day 12
PreloadLoads graphics in advance Day 18
LayoutProvides 2-D item placement Day 18

The Label Control

You've seen examples of the label control already today. The brief glimpse provided in Figure 10.1 showed one important distinguishing trait of most controls: They typically enable you to perform more than you could with just the HTML language. The first sample with the label control shows that it can display text at an angle. If you restricted your authoring efforts to present-day HTML, you would not be able to position text in this manner; boring old horizontal positioning would be your only alternative. Of course, you could incorporate a graphic that displays an image of angled text. An image, however, would not give you the rich ability to make your page more interactive that the label control provides. You saw the first taste of this in Figure 10.2; the label can provide a response when it's clicked (assuming that you write the code to do this).

Properties, Methods, and Events Supported by the Label

The label has many ways to make your pages alive. You must have a full awareness of all the properties, events, and methods of the label control to use it effectively.

Properties

The purpose of the label control is to display text. The text can be displayed with a lot of different characteristics-color, an angled alignment, the font of your choice, bold text, and more. As you have seen, you define properties of the label in the object declaration as shown in Listing 10.4.


Listing 10.4. Object declaration for a label with parameters.
<OBJECT
    classid="clsid:99B42120-6EC7-11CF-A6C7-00AA00A47DD2"
    id=lblSample
    width=125
    height=125
    align=left
    hspace=20
    vspace=0
>
<param name="angle" value="65" >
<param name="alignment" value="3" >
<param name="BackStyle" value="0" >
<param name="caption" value="Master the Label!">
<param name="FontName" value="Arial">
<param name="FontSize" value="17">
<param name="FontBold" value="1">
<param name="FontItalic" value="0">
<param name="FontUnderline" value="0">
<param name="FontStrikeout" value="0">
<param name="ForeColor" value="0">
</OBJECT>

Properties specified in the object declaration are simply initial properties. You do not have to specify every single property here. If you don't specify a property, it will simply assume a default value. These properties determine how the label will appear when it is first drawn on the page at the initial page load. After that point, the script code can control properties in response to user interaction. Table 10.3 lists all the properties for the label.

Table 10.3. Label properties.

Property
Description
Caption The text that is to be displayed
Angle The degree at which to display the text, in counter-clockwise degrees
Alignment The manner in which text is aligned in the control
 0: left aligned
 1: right aligned
 2: centered
 3: top aligned
 4: bottom aligned
BackStyle Background appearance of label
 0: transparent; you see the page underneath the label
 1: opaque; you see the label background and not the page beneath it
FontName Name of a TrueType font
FontSize The size of the font
FontItalic 0: no italicized font
 1: font will be italicized
FontBold 0: no bold font
 1: font will be bold
FontUnderline 0: no underline under font
 1: font will be underlined
FontStrikeout 0: no strikeout through font
 1: font will have strikeout (line through middle of characters)
ForeColor The color of the label text

Note
If you have used other visual programming environments, you probably have used properties of controls to dynamically control the positioning of the control. At the time of this writing, this level of positioning is supported only if you use the Layout Control to facilitate positioning, as described on Day 18. Direct 2-D control is not supported. In other words, you cannot modify a top and a left property of a label from your program to move the location of the label on the page. A label control is placed on the page in the order in which it is defined within that page. If you use the layout control, you can carry out such manipulations.
The properties, events, and methods presented in this book are intended to show you the capabilities of a control. This book does not necessarily present every possible setting supported. Check the Microsoft Web site documentation or use a control tool like those described earlier today to verify the complete set of available properties, methods, and events.

A Note on Handling Angles

Because a circle has 360 degrees, an angle can be defined in degrees from -360 to 360. An angle of 0 degrees indicates a label that reads straight out to the right, along what is a conceptual X-origin line. An angle of 90 degrees indicates a label that reads straight up. When you specify an angle as a negative number, it is displayed in terms of a clockwise rather than counterclockwise angle from the origin. An angle of -30 degrees, for example, will be displayed the same as an angle of 330 degrees.

360 degrees indicates a complete rotation around the origin. You can even specify an angle greater than 360 degrees or less than -360 degrees. In angular terms, this means that one or more complete rotations are made around the axis before the angle rotation. The angle is displayed in terms of the remainder angle after multiples of 360 degrees are subtracted (called the modulo value). In other words, 390 degrees is displayed as a 30 degree angle (because the 360 rotation is removed).

When you assign a value to the label angle property, any values under -360 or over 360 are stored as the corresponding modulo angle between -360 and 360. For example, if you assign 390 degrees to a label's angle property and then use a message box statement to inspect the value of the property, you will see that VBScript has stored the equivalent 30 degree representation for the angle. Likewise, if you have an angle of 350 in the angle property and add 20 to it, you will end up with an angle of 10 degrees in the angle property.

A Note on Handling Colors

Most of the properties are either fairly self-explanatory or best understood through simple trials. However, one property that does require a bit more explanation is ForeColor. This property determines the color of the label text. Similar properties are used in many other controls. You must specify the ForeColor in numeric terms. The number you supply represents the color mix based on the amount of blue, green, and red that go into that color. The amount of each color component can range from 0 to 255. If you know hexadecimal (base 16) arithmetic, you realize that this is exactly the range of values you can represent in two hexadecimal digits (which takes up a byte in a computer). Therefore, each color component can be represented in terms of two hexadecimal digits, and they can be combined to make a grand total that represents the entire mix.

Consider a color that is all blue with no green or red:

Blue component = 255 = hexadecimal &FF
Green component = 0 = hexadecimal &00
Red component = 0 = hexadecimal &00
Combined blue/green/red representation in hex = &FF0000
Combined blue/green/red representation converted to decimal = 16711680

To set the color of a label to blue, you would use a statement like the following:

lblAd.ForeColor = 16711680

Alternatively, you could use hexadecimal notation to achieve the same effect:

lblAd.FforeColor = &FF0000

Note
An & is used to signify the start of a hex number in VBScript and many other languages as well. &FF means a hexadecimal FF, which equals 255 in decimal notation. You can refer to a basic computer math book if you want more details on converting between hexadecimal and decimal systems.

In either case, you'd end up with a blue label. The same values you use to specify the ForeColor within your code statements can also be used in the object declaration when you specify the ForeColor parameter.

It can be a tedious, error-prone matter to designate color values for properties. It's a challenge to figure out which values to use, and when you type in a long cryptic-looking number, there's always a chance you'll transpose digits. It is easier to type in colors in terms of hex digits using the &H prefix than to type decimal digits. Because the hex digits are easy to view in terms of the separate byte components, you can more easily picture the color mix. Even this approach is still somewhat cryptic and error prone, though. Fortunately, constants come to your rescue. At the time of this writing, there were not yet any intrinsic color constants for script statements. The intrinsic constants you can use with HTML work for the object <PARAM> attributes but do not work within VBScript. You can define your own variable values and treat them as constants, however. You can simply supply color constants for your favorite colors at the beginning of your script code, as shown in Listing 10.5.


Listing 10.5. Setting up color constants at the start of a script.
<SCRIPT LANGUAGE="VBSCRIPT">
<!--
   dim BLUE, GREEN, YELLOW, RED, BLACK

   ' Assign these global values once, then use as constants
   BLUE = &HFF0000   ' Blue = 255, Green = 0, Red = 0
   GREEN = &HFF00  ' Blue = 0, Green = 255, Red = 0
   YELLOW = &HFFFF  ' Blue = 0, Green = 255, Red = 255
   RED = &HFF  ' Blue = 0, Green = 0, Red = 255
   BLACK = &H00  ' Blue = 0, Green = 0, Red = 0

Events and Methods

Properties alone are often not enough to do all you must do with a control. When you want to cause the control to execute specific actions or respond to specific actions it generates, you must turn to events and methods. The label control has only two of relevance:

Event: Click is triggered when the user clicks on the label.
Method: AboutBox is a method you call from your script code to display the label's About box.

As you saw in Listing 10.3, whenever the user clicks the label, any script code associated with the Click event subroutine is executed. All you have to do to define a Click event subroutine in your code is start the name with the name of the control object and after an underscore, conclude it with the name of the event, Click.

The About method is common to many controls but is used less frequently. This method displays an About box with information about the label control when you call it from your code.

The Label-Tweaker Sample: Putting Properties to Work

If all you could do with the label control is set its properties in the object declaration and govern how the control first appears, it might have little value to you. The page really starts to seem alive and responsive, however, when your code manipulates the control after the page is loaded and your user interacts with it. The application pictured in Figure 10.3 demonstrates this potential.

Figure 10.3 : The Label-Tweaker sample.

This application is called the Label Tweaker. Tweak is an old programming expression that refers to slightly modifying a program to observe the results. The Label Tweaker enables you to tweak one property value at a time and see firsthand the changes that result in the label control. You simply specify the property in a text box input control and then click the Apply Properties button. All property values are reassigned, and the label control appearance is modified accordingly. Listing 10.6 shows the object declaration that defines the initial appearance of the label.


Listing 10.6. The object declaration for the Label-Tweaker label.
<OBJECT
    classid="clsid:99B42120-6EC7-11CF-A6C7-00AA00A47DD2"
    id=lblSample
    width=125
    height=125
    align=left
    hspace=20
    vspace=0
>
<param name="angle" value="65" >
<param name="alignment" value="3" >
<param name="BackStyle" value="0" >
<param name="caption" value="Master the Label!">
<param name="FontName" value="Arial">
<param name="FontSize" value="17">
<param name="FontBold" value="1">
<param name="FontItalic" value="0">
<param name="FontUnderline" value="0">
<param name="FontStrikeout" value="0">
<param name="ForeColor" value="0">
</OBJECT>

Note
The Label-Tweaker sample program is available on the CD-ROM that comes with this book in file Lbltwkr.htm.

An input form collects the desired property values from the user. After the user selects the command button to assign properties, the values stored on the input form are assigned to the label properties. Figure 10.4 shows the result of specifying new values and selecting the command button.

Figure 10.4 : Label Tweaker after user-supplied values have been assigned to label properties.

Listing 10.7 shows the code that modifies the label properties when the user presses the command button. Each property value is simply transferred from the text box where it was specified to the control property itself by the assignment statement.


Listing 10.7. Code that modifies label properties.
Sub cmdApply_OnClick
    'This routine is called when the user clicks the apply button.
    ' It applies the property values specified on the form to
    ' the label control.

     dim frmCurrent

     set frmCurrent = document.frmProperties

     lblSample.caption = frmCurrent.txtCaption.Value
     lblSample.angle = frmCurrent.txtAngle.Value
     lblSample.alignment = frmCurrent.txtAlignment.Value
     lblSample.BackStyle = frmCurrent.txtBackStyle.Value
     lblSample.FontName = frmCurrent.txtFontName.Value
     lblSample.FontSize = frmCurrent.txtFontSize.Value
     lblSample.FontBold = frmCurrent.txtFontBold.Value
     lblSample.FontItalic = frmCurrent.txtFontItalic.Value
     lblSample.FontUnderline = frmCurrent.txtFontUnderline.Value
     lblSample.FontStrikeout = frmCurrent.txtFontStrikeout.Value
     lblSample.ForeColor = frmCurrent.txtForeColor.Value

end sub

The Set statement simply enables you to use a variable name in place of the longer document and form descriptor that designates the form used to collect input. Set fills the variable with the data that follows, which in this case is the form object. In subsequent references to form data, you can use just the variable rather than the lengthier document designator. This is just a convenient form of shorthand often used with document definitions.

Using a Control's Properties When the Page Loads

This subroutine modifies the label and causes its appearance to change on the page. Because the subroutine references object properties, the script containing this subroutine had to appear after the object definition. One more aspect of this program helps it to convey the state of the control properties to the user. It starts out with a display of all the current label control properties. This could have been accomplished simply by setting the initial value attribute of the input text controls to a value that matched the object declaration. In that case, however, every time the object declaration changed, the input text control value would have to change, too. Instead, the program automatically determines the state of the label control on startup. This is accomplished through the code shown in Listing 10.8.


Listing 10.8. Startup code that captures initial label control property settings.
<SCRIPT>
<!--
'--------------------------

    ' Startup Code

    'This block of code is executed when the page is generated, since
    '  it appears in the main body of the script rather than in a subroutine.

    'Display the initial property settings of the label control
    Call ShowStartingProperties


    ' End of Startup Code
    '-----------------

    Sub ShowStartingProperties

      dim frmCurrent

      set frmCurrent = document.frmProperties
      frmCurrent.txtCaption.Value = lblSample.caption
      frmCurrent.txtAngle.Value = lblSample.angle
      frmCurrent.txtAlignment.Value = lblSample.alignment
      frmCurrent.txtBackStyle.Value = lblSample.BackStyle
      frmCurrent.txtFontName.Value = lblSample.FontName
      frmCurrent.txtFontSize.Value = lblSample.FontSize
      frmCurrent.txtFontBold.Value = lblSample.FontBold
      frmCurrent.txtFontItalic.Value = lblSample.FontItalic
      frmCurrent.txtFontUnderline.Value = lblSample.FontUnderline
      frmCurrent.txtFontStrikeout.Value = lblSample.FontStrikeout
      frmCurrent.txtForeColor.Value = lblSample.ForeColor
    end sub

-->
</SCRIPT>

All the input text controls are filled with the label control property values when the program starts. This ensures that the display of properties is in sync with the actual state of the control. This block of code is located after the object and form declaration. Because it is called at startup (the main script code is not in a procedure), it needs to follow these declarations to reference them.

Change Properties Through the Click Event

The sample program also uses the label Click event to modify properties. When the label is clicked, the code in Listing 10.9 is executed. This code modifies the label's angle and shows the change in the input text control.


Listing 10.9. Modifying the label angle through the Click event.
Sub lblSample_Click
    ' This routine is called when the label is clicked.
    '    It will alter the angle of the label by 5 degrees.

     ' Advance the angle
     lblSample.angle = lblSample.angle + 5

     ' Reflect the current setting back in the property display
     document.frmProperties.txtAngle.Value = lblSample.angle

end sub

Experimenting with the Script

At this point, two things will probably help you to understand the program well. The first is to study the source code carefully. The second is to spend time modifying each and every property value through the program interface and observe the changes that occur when you click Apply Properties. Also, click the label itself and cause the Click event to occur. You might find that you get new ideas about possible ways to use this control for your own scripts as you observe the properties changing and cause those changes firsthand.

When Painting Updates Occur On-screen

You can note a couple interesting things about controls and VBScript with this sample program. The first is that updates to the page caused by your script code don't take effect until all code has completed. If your first statement changes the caption of a label and then 50 more statements follow, your user won't see the update on-screen until after the 51st statement has been completed and the block of code has been completely executed. VBScript subroutines are processed in their entirety before screen updates take place.

Note
If you've worked with Visual Basic 4.0 or Visual Basic for Applications, you might be accustomed to using the DoEvents statement that gives other parts of your code a turn at executing their processing and in some cases, affects screen paint strategies. This statement is not available in VBScript.

When a Page Is Reinitialized

Another issue of concern or curiosity to most programmers is the point in time that a page and the code in it is initialized. When a page is first loaded, it is rendered onscreen, and any object declarations and startup code (within a script statement but not inside procedures) are executed. What happens if a Web page user advances to another page and then returns to return to the original page? Label Tweaker can demonstrate that no reinitialization takes place on the return.

To verify this, first load some other Web page in the browser. Then start Label Tweaker and observe the initial appearance of the label. Change the color and the angle of the label and click the Apply Properties button to make these changes take effect. Then select the previous page tool button to back up to the previous page you viewed. From there, select the advance page tool button and return to Label Tweaker. If the page was reloaded and reinitialized, you would see it back in its original startup state at this point. The property values you established in the object definition would be in effect. Instead, you will see the same appearance that changed after you selected Apply Properties.

You can select the browser refresh option with View | Refresh to cause a reload in Internet Explorer. When you do, the change in appearance confirms that only at this point has the page been reloaded and the label reinitialized. This is an important point of script programming. Your script programs retain their state once the page is loaded, even as the user moves between other pages and tasks. When you modify a control, its properties remain in the modified state on that page until the page is reloaded.

The Tutorial Sample: A Highly Interactive Script

So far, you've seen the label control used in ways that might not be exactly what you'll need in your own scripts. The first example with the store ad wasn't very interactive. The second sample program, Label Tweaker, was more for experimenting than for any true-to-life purpose you're likely to need for your own scripts. Now it's time to see how you can use the label control to create a highly interactive Web page.

A tutorial program called the VBScript ActiveX Tutorial demonstrates how you can use the label control to give your users a high degree of feedback during their interaction with your scripts. Figure 10.5 shows the initial appearance of the page built around this script program.

Figure 10.5 : The VBScript ActiveX Tutorial Program.

A series of questions is displayed on the screen using standard HTML. Next to each question is a standard input text control to collect the answer. To the right of that is a column of hints, displayed with the label control. All question-related information is also presented within a HTML table to help neatly align the columns of information.

Note
The tutorial program is available on the CD-ROM in the file interact.htm.

When the user interacts with this program, she enters her response in the corresponding text box for each question and then presses the Provide Feedback command button. This command button triggers code that evaluates each answer. If an answer is correct, a green label displays Correct! If an answer is incorrect, a red label provides the correct answer. To provide a high degree of visual cue feedback, a correct answer changes the angle of the feedback label to point slightly upward with a jaunty air. If an answer is incorrect, the feedback label angle changes to droop slightly downward. A label at the bottom of the feedback area shows the total number of correct answers. Figure 10.6 shows the result from entirely incorrect responses. Compare that to Figure 10.7, which shows the results when every question is answered correctly.

Figure 10.6 : Results feedback for wrong answer.

Figure 10.7 : Results feedback for correct answers.

The degree to which the feedback of this program impresses you probably depends on your background. If you're coming to VBScript from a traditional programming background, you might think, "This interactivity is very much like what I can already do with a Windows program." If you're approaching VBScript from a heavy Web page development background, you might be thinking, "This really lets me do a lot more than I ever could before in my Web pages." Both of these perspectives are accurate. VBScript integrates controls and provides programmability much like its parent product Visual Basic has for some time in the Windows environment. VBScript now extends this power to the Web page.

Listing 10.10 shows the code that assesses the answers to the tutorial questions and provides the feedback. A comparison is performed on each text box answer. For the sake of the example, the comparison has been kept very simple. In an actual tutorial, you would probably perform much more extensive comparisons, converting the response to uppercase, checking for close variations on the correct answer, and so on. With this sample program, if an exact match occurs on the answer, it is considered a correct response.


Listing 10.10. Providing feedback based on responses.
<SCRIPT LANGUAGE="VBSCRIPT">
<!--

    Sub cmdFeedback_OnClick
    'This routine is called when the user clicks the feedback button.

        dim Correct

        Correct = 0

        ' Change all feedback labels to italic rather than bold
        lblFeedback1.fontbold = 0
        lblFeedback1.fontitalic = 1
        lblFeedback2.fontbold = 0
        lblFeedback2.fontitalic = 1
        lblFeedback3.fontbold = 0
        lblFeedback3.fontitalic = 1


        ' Assess Question 1
        if txtQuestion1.Value = "<OBJECT>" then
            ' Correct response
            Correct = Correct + 1
            lblFeedback1.angle = "10"
            lblFeedback1.fontsize = "24"
            lblFeedback1.caption = "Correct!"
            lblFeedback1.ForeColor = "65280"
        else
            ' Incorrect response
            lblFeedback1.angle = "350"
            lblFeedback1.caption = "The <OBJECT> tag"
            lblFeedback1.ForeColor = "255"
        end if

        ' Assess Question 2
        if txtQuestion2.Value = "<PARAM>" then
            ' Correct response
            Correct = Correct + 1
            lblFeedback2.angle = "10"
            lblFeedback2.fontsize = "24"
            lblFeedback2.caption = "Correct!"
            lblFeedback2.ForeColor = "65280"
        else
            ' Incorrect response
            lblFeedback2.angle = "350"
            lblFeedback2.caption = "The <PARAM> tag"
            lblFeedback2.ForeColor = "255"
        end if

        ' Assess Question 3
        if txtQuestion3.Value = "ID" then
            ' Correct response
            Correct = Correct + 1
            lblFeedback3.angle = "10"
            lblFeedback3.fontsize = "24"
            lblFeedback3.caption = "Correct!"
            lblFeedback3.ForeColor = "65280"
        else
            ' Incorrect response
            lblFeedback3.angle = "350"
            lblFeedback3.caption = "The ID attribute"
            lblFeedback3.ForeColor = "255"
        end if

       ' Show the results
       lblResults.caption = cstr(Correct) & " out of 3 correct!"

    end sub
-->
</SCRIPT>

Once a correct response occurs, the label angle, caption, font size, and ForeColor are all adjusted accordingly. Likewise, if an answer is incorrect, the angle, caption, and ForeColor are adjusted for incorrect response feedback. The lblResults label that is updated in the last line of the script illustrates a particularly useful technique. You can make a response appear to materialize for your user just when you want it to. The lblResults label does not initially appear to the user because the following parameter is used to declare the starting object caption:

<param name="caption" value="">

When you want a caption to appear, you simply assign one in your code, and presto! The user sees text where there was none before. This program makes use of many labels-four to be exact-to provide a dynamic page that updates with user feedback. In the old Web programming model, you probably would have provided such function with at least two separate Web pages, one of them custom-generated by a CGI script on the server. The simple addition of the label control and VBScript enable you to integrate all this feedback into one relatively simple page.

Note
A rather interesting behavior occurs with the label control if you don't include any parameter tag for the caption in your object declaration. When the label is drawn on screen, it will appear with the caption "Default!" You can still assign values to properties even if they are not declared with the parameter tag in an object declaration. You can change the caption at some point in your program if you start with this default caption. However, if you don't want to generate a caption until some interaction with your program occurs, you would prefer that your user see nothing for the label rather than the confusing "Default" on screen. Setting the parameter equal to the empty string, as defined previously, solves this problem.

Summary

Today's lesson provided an introduction to objects and ActiveX controls. An object is a component to be integrated into the page. An ActiveX control is one specific kind of object. A draft standard that details how an object should be defined within a Web page was outlined in detail. The <OBJECT> tag declares the object, along with standard attributes that define a generic object. In addition, the <PARAM> tag defines properties uniquely provided by the specific object that has been declared.

The ActiveX control technology evolved from the concepts of older Visual Basic VBX controls and the more recent OCX controls based on Microsoft's object linking and embedding (OLE) standards and technology. The ActiveX control encompasses OCX controls, which can be utilized in Web pages through VBScript.

The lesson then examines the ActiveX label control in detail, outlining the properties, methods, and events of the control. With the label control, you can fully control the appearance of a label placed on a Web page. This includes control of the color, the font, and even the angle of the text. The lesson provides several examples, including a program that allows experimentation with changing the various label properties and a tutorial that demonstrates the high degree of user feedback that the pages that integrate this control can provide.

Q&A

Q
Which object attribute provides a name for the object that your code will use to reference the object?
A
The ID attribute designates a name for the object.
Q
Are ActiveX controls available from sources other than Microsoft?
A
Yes, you can purchase ActiveX controls from other vendors or even write them yourself if you have adequate expertise and tools.
Q
Can a label be blank initially so the user doesn't see it until some later point in the script?
A
Yes, just supply an empty caption by providing two double quotes with nothing between them for the caption parameter declaration of the object. The tutorial program used this technique. Keep in mind that you must supply an empty string. If you omit the caption parameter all together, the word "default" is supplied as the starting caption.
Q
Does a label control have any useful events?
A
Yes, you can use the Click event to provide code that is executed when a label is clicked.

Workshop

Take a Web page that you have previously developed and add a label control somewhere within it. Experiment with various properties, such as different colors and angles. Add several input command buttons, and write code associated with each button to provide a different angle and color scheme for the label when you click it. Assess your previously developed Web pages and see if you can design one where a dynamically updated label would provide valuable feedback to the user, instead of just providing a jazzier look.

Quiz

Note
Refer to Appendix C, "Answers to Quiz Questions," for the answers to these questions.

  1. Given the object declaration below, write code to change the caption of this object to "Kenny Jasper" whenever it is clicked:

    <OBJECT
        classid="clsid:{99B42120-6EC7-11CF-A6C7-00AA00A47DD2}"
        id=lblTester
        width=125
        height=125
        align=left
        hspace=20
        vspace=0
    >
    <param name="angle" value="65" >
    <param name="alignment" value="3" >
    <param name="BackStyle" value="0" >
    <param name="caption" value="Master the Label!">
    <param name="FontName" value="Arial">
    <param name="FontSize" value="17">
    <param name="FontBold" value="1">
    <param name="FontItalic" value="0">
    <param name="FontUnderline" value="0">
    <param name="FontStrikeout" value="0">
    <param name="ForeColor" value="0">
    </OBJECT>
  2. Use the label control declared in the previous question for this question as well. Write an If statement that will change the caption of the label to Brooke only if the current angle of the label is between 20 and 40 degrees inclusive. If the caption change is not made, increase the angle by 10 degrees. (Don't worry about which subroutine the If statement should go in.)