Share via


Understanding Scriptlets and Behaviors

This content is no longer actively maintained. It is provided as is, for anyone who may still be using these technologies, with no warranties or claims of accuracy with regard to the most recent product version or service release.

A scriptlet is a lightweight, reusable Component Object Model (COM) component that consists of HTML code and script and is created according to certain conventions. A behavior is a lightweight component that encapsulates specific functionality. When applied to an HTML element, a behavior enhances the element's default behavior.

Scriptlets and behaviors are very similar in that they both contain script in a separate document that exposes functionality that can be used in a Web page. They differ in that behaviors are STYLE attributes that point to a separate file containing script that is called in response to an event associated with an HTML element. Scriptlets, on the other hand, can be used for almost anything you can do with script in a Web page.

Scriptlets are supported in Internet Explorer 4.0 or later, and behaviors are supported in Internet Explorer version 5 or later. Deciding when to use a scriptlet and when to use a behavior depends on what you are trying to accomplish and what browser you are writing for. If your users are running Internet Explorer 4.x, scriptlets are your only choice. If you want to create a self-contained component for use in HTML, a DHTML scriptlet makes sense. If you want to add a lightweight component to be used as a STYLE attribute, a behavior is a good choice.

Creating Scriptlets

A scriptlet is an HTML code file that has either an .sct or an .htm extension. You can create scriptlets by using HTML code and VBScript code, JScript code, or both, and you can create them in any HTML editor. You can also create scriptlets by using the Microsoft Scriptlet Wizard. If you have worked with the Class Builder in Microsoft Visual Basic version 5.0 or 6.0, you are already familiar with how this wizard works. The wizard takes you through the steps required to create the basic HTML code required for a scriptlet, along with a sample container file containing the HTML code required to reference the scriptlet from another Web page. You can download the Scriptlet Wizard from the Microsoft Scripting Technologies Web site at http://msdn.microsoft.com/scripting.

What Kind of Scriptlet Should I Create?

There are two basic types of scriptlets: those that have a user interface (DHTML scriptlets) and those that do not (code-only scriptlets). Scriptlets that have a user interface are encapsulated script and DHTML code and are designed to display their user interface in another HTML page. For example, you could create a scriptlet that displays a digital clock or a calendar. The display elements and all the code necessary to make the display work properly are encapsulated within the scriptlet so that it can be used again and again just like any other COM component.

Scriptlets without a user interface are Web pages in which script procedures have been written so that these procedures behave like methods and properties of an object. This type of scriptlet is analogous to a custom object created from a VBA class module. Like a class module, the scriptlet contains a number of procedures, some of which are exposed to other objects as methods or properties and others that are accessible only by other procedures within the scriptlet itself.

The reasons for creating reusable objects that contain script are the same as the reasons for creating reusable objects through VBA. For a complete discussion of the benefits of reusable code objects, see Chapter 9, "Custom Classes and Objects." For a complete discussion of scriptlets, see the Scriptlet Technology Web site at http://msdn.microsoft.comsdk/inetsdk/help/scriptlets/scrlt.htm.

Working with DHTML Scriptlets

A DHTML scriptlet is a Web page that exposes a user interface that can be used from another Web page. To create a DHTML scriptlet, you simply create a Web page that displays the user interface you want to save as a scriptlet. You then add any script necessary to make the user interface fully functional. That is all there is to it. For example, the following sample shows all the HTML code and script required to create and display a digital clock on a page:

<HTML>
<HEAD>
<SCRIPT LANGUAGE="VBScript">
<!--
Sub InitDigiTimer
   ' Specify that the MoveTime procedure should be
   ' called at 1-second intervals.
   window.setInterval "MoveTime", 1000
End Sub

Function MoveTime()   
   document.all("displayTime").innerText = time()
End Function

Sub window_onload()
   InitDigiTimer
End Sub
-->
</SCRIPT>
</HEAD>

<BODY>
<DIV   ID=displayTime
      STYLE=   "position:absolute;
             width: 120;
             height: 20;
             border:solid;
             border-color:lightblue;
             border-left-width:thin;
             border-right-width:thin;
             background-color:darkblue;
             color:yellow;
             text-align:center;
             font-family:arial;
             font-weight:bold">
</DIV>
</BODY>
</HTML>

Figure 12.3 shows how this HTML code is rendered in the browser.

Figure 12.3 Digital Clock Scriptlet

When you use this file as a scriptlet, only the clock and its related formatting appear in the container Web page. For example, you could name this file DateTime.htmt and use it as a scriptlet from another Web page by inserting the following <OBJECT> tag in the container page:

<OBJECT   ID="scrltCode2"
         STYLE= "position:absolute;
                  width:150;
                  height:40;"
         TYPE="text/x-scriptlet"
         DATA="DateTime.htm">
</OBJECT>

The only mandatory <OBJECT> tag attributes to create a DHTML scriptlet are TYPE and DATA. The TYPE attribute setting will always be "text/x-scriptlet". The DATA attribute should always contain the path and name of the file you are referencing as a scriptlet. If you want to change the design of the clock, you need only change the settings for the STYLE attribute in the DateTime.htm file. You can position the clock anywhere on the container page by enclosing the <OBJECT> tags shown above in <DIV> tags with STYLE attribute settings indicating precisely where on the page you want the clock to appear.

Working with Code-Only Scriptlets

There are two ways to create this kind of scriptlet. You can create an HTML file with <SCRIPT> tags to contain your custom procedures, or you can use the Scriptlet Wizard. In either case, you are creating a basic template with procedures that represent the public properties and methods of the object along with any private procedures available only to other procedures in the scriptlet object itself.

The following sample illustrates the HTML code and script for a very simple (no provision is made for handling errors) code-only scriptlet named GetRecords.htm. This scriptlet is designed to return an ActiveX Data Objects (ADO) Recordset object to the calling function in the container Web page. The GetRecords.htm file is available in the ODETools\V9\Samples\OPG\Samples\CH12 subfolder on the Office 2000 Developer CD-ROM.

You create properties for the scriptlet by adding the get_ (read) or put_ (write) prefix to the property name in the Function procedure. If you create both get_ and put_ procedures for a property, the property will be read/write. Using only one of the two designators creates a read-only or write-only property. Procedures created with the get_ and put_ designators are analogous to the Property Get and Property Let procedures used in a VBA class module. You specify default values for properties by setting each property to some value at the top of the script block, before the procedures are defined.

You create public methods for the scriptlet by adding the public_ prefix to the name of the method in the Function procedure. Procedures that do not use the public_ prefix will be available only to other procedures within the scriptlet and will not be visible from the container Web page.

<HTML>
<HEAD>
<TITLE>GetRecords Scriptlet</TITLE>
</HEAD>

<SCRIPT LANGUAGE="VBScript">
<!--
' Initialize properties to their default values.
Dim p_provider
Dim p_databasePath

p_provider = "Microsoft.Jet.OLEDB.4.0"
p_databasePath = "c:\program files\microsoft office\office\samples\northwind.mdb"

Function get_provider()
   get_provider = p_provider
End Function

Function put_provider(newValue)
   p_provider = newValue
End Function

Function get_databasePath()
   get_databasePath = p_databasePath
End Function
Function put_databasePath(newValue)
   p_databasePath = newValue
End Function

Function public_GetRecordset(strSQL)
   Dim rstRecordset
   Dim cnnConnection

   Set cnnConnection = CreateObject("ADODB.Connection")
   cnn.Provider = p_provider
   cnn.Open p_databasePath

   Set rstRecords = CreateObject("ADODB.Recordset")
   rstRecords.Open strSQL, cnn, 1, 3
   Set public_GetRecordset = rstRecords
End Function
-->
</SCRIPT>

<BODY>
</BODY>
</HTML>

In the container Web page, you create a reference to this scriptlet by using an <OBJECT> tag as shown earlier for DHTML scriptlets:

<OBJECT
   ID="NWIND"
   STYLE="   position:absolute;
            width:0;
            height:0;
            top:0;
            left:0;"
   TYPE="text/x-scriptlet"
   DATA="GetRecords.htm">
</OBJECT>

The <OBJECT> tag is using an ID attribute setting of "NWIND", and you use this identifier when calling procedures in the scriptlet. For example, you would use the following script in the container Web page to call the custom GetRecordset method of the referenced scriptlet.

<SCRIPT LANGUAGE="VBScript">
<!--
Sub DisplayCustomerInfo()
   Dim strCountry
   Dim strSQL
   Dim rstRecords

   strCountry = document.all("txtCustomerCountry").value
   strSQL = "SELECT * FROM Customers WHERE Country = '" & strCountry & "'"
   Set rstRecords = NWIND.GetRecordset(strSQL)
   ' Work with the returned records here.
End Sub
-->
</SCRIPT>

This scriptlet is useful and flexible enough to work against any number of data sources. All you have to do is specify a different data source by setting the properties and then return matching records defined by your strSQL variable. As you can see from the preceding example, using scriptlets can be a very powerful technique for encapsulating related script procedures into reusable objects.

How Scriptlets and Web Browser Security Interact

In a security-aware host such as Internet Explorer 4.0 or later, a scriptlet and any controls contained within it are subject to Internet Explorer security. To set the security level in Internet Explorer, click Internet Options on the View menu (version 4.0x) or the Tools menu (version 5 or later), and then click the Security tab.

On a user's machine, the security level for the zone containing the scriptlet's server must be set to either Medium or Low. If the security setting is High, the scriptlet will not be downloaded to the user's computer. If custom security settings are specified for a zone by clicking Custom Level on the Security tab in the Internet Options dialog box, both Script ActiveX controls marked safe for scripting and Initialize and script ActiveX controls not marked as safe must be set to either Prompt or Enable.

The same guidelines apply to any controls that the scriptlet contains, including other scriptlets, especially if the scriptlet contains controls that reside on a server in a different zone.

Therefore, when you distribute an application that uses a scriptlet, make sure that users set the security settings in their copy of Internet Explorer to the correct level to allow them to use your scriptlets.

For more information about the security settings in Internet Explorer, see Internet Explorer Help.

Understanding Behaviors

Scriptlets and behaviors provide a way to create reusable components you can use on a Web page. They allow you to encapsulate and reuse blocks of code and to separate the script in a page from its content. There are two types of behaviors you can use with your Web pages: custom behaviors and built-in behaviors.

Custom Behaviors

Custom behaviors are integrated with Internet Explorer through an interface handler. Internet Explorer provides the Behavior Handler (a type of interface handler) as the way a behavior scriptlet can communicate with the page that references it. The Behavior Handler allows the behavior scriptlet to expose custom events, access the containing page's DHTML object model, and receive notification when an event has occurred in the containing page. For complete information about the Behavior Handler, see the Behavior Handler Reference at http://msdn.microsoft.com/workshop/components/scriptoid/reference/behavior.htm.

The basic parts of a custom behavior scriptlet are <SCRIPTLET> tags, <IMPLEMENTS> tags, and <SCRIPT> tags, which are saved in a file that has an .sct extension. The <IMPLEMENTS> tag uses a TYPE attribute of "Automation". The <SCRIPT> tags contain the script you want to associate with the behavior.

<SCRIPTLET>
<!--
   <IMPLEMENTS Type="Behavior">
   </IMPLEMENTS>
   <SCRIPT Language="VBScript">
      ' Add your script here.
-->
   </SCRIPT>
</SCRIPTLET>

Once you have created this basic framework, you can use DHTML objects and methods to create custom events, synchronize with events generated by an element in the containing page, or expose custom properties and methods. The following example serves to illustrate the concepts behind creating a custom behavior scriptlet. This behavior uses the attachEvent method to monitor events from the containing page and execute script when the specified events occur:

<SCRIPTLET>
   <IMPLEMENTS Type="Behavior">
   </IMPLEMENTS>
   <SCRIPT Language="VBScript">
<!--
      Dim previousColor

      attachEvent("onmouseOver", event_onmouseOver)
      attachEvent("onmouseOut", event_onmouseOut)

      Function event_onMouseOver()
         previousColor = style.color
         style.color = "red"
      End Function

      Function event_onMouseOut()
         style.color = previousColor
      End Function
-->
   </SCRIPT>
</SCRIPTLET>

When this behavior is connected to an HTML element as a STYLE attribute, the script it contains runs in response to the mouseOver and mouseOut events. When the mouse pointer moves over the element, the element color is changed to red and the element's original color is saved in the previousColor variable. When the mouse pointer moves off the element, the original color is restored. You can add this behavior to an HTML element by specifying the behavior scriptlet as a STYLE attribute of the element, as shown in the following example:

<HTML>
<TITLE>Behavior Demo</TITLE>
<HEAD>
<STYLE>
   .HiLite {behavior:url(hilite.sct)}
</STYLE>
</HEAD>
<BODY>
This word is <SPAN style=hilite>CAPITALIZED</SPAN>. Move the mouse pointer over it to change its color.
</BODY>
</HTML>

Built-in Behaviors

You can also take advantage of the built-in, or default, behaviors included with Internet Explorer. These behaviors are available directly from the browser; you can use them without writing any additional external components yourself. The behaviors implemented by Internet Explorer are listed in the following table.

Built-in behavior Description
anchor Enables browser navigation to a folder view.
clientCaps Provides information about the capabilities Internet Explorer supports, as well as a means to install browser components on demand.
download Provides a means to download a file and notify a callback function when the download is complete.
homePage Contains information about a user's home page.
httpFolder Contains script features that enable browser navigation to a folder view.
saveFavorite Allows the current state of a page to be saved when it is added to Favorites.
saveHistory Allows the current state of the page to be saved when the user navigates away from the page.
saveSnapshot Allows persistence of information (form values, styles, dynamically updated content, and script variable values) when a page is saved locally.
userData Allows persistence of information across sessions by writing data to XML storage.

You reference a built-in behavior by using the behavior's name and #default#BehaviorName as the value for the url argument, as shown in the following example:

<HTML>
<TITLE>Built-in Behavior Demo</TITLE>
<HEAD>
<STYLE>
   .saveFavorite {behavior:url(#default#savefavorite)}
</STYLE>
</HEAD>
<BODY>
<INPUT class=saveFavorite type=text width=35 value="I am a text box.">
</BODY>
</HTML>

For more information about built-in behaviors, see Chapter 9, "Custom Classes and Objects," the Component Development section of the Microsoft Site Builder Workshop Web site at http://msdn.microsoft.com/workshop/default.asp, and the DHTML Behaviors section of the Microsoft Site Builder Workshop Web site at http://msdn.microsoft.com/workshop/c-frame.htm?/workshop/author/default.asp.