Export (0) Print
Expand All
11 out of 28 rated this helpful - Rate this topic

About Element Behaviors

This topic documents a feature of Binary Behaviors, which are obsolete as of Internet Explorer 10.

Element behaviors are one of the most significant new capabilities in Microsoft Internet Explorer 5.5. They provide the capability to define custom elements, which can be used in the same way as normal HTML elements in a Web page. An element behavior can be written in script using an HTML Component (HTC) file, or it can be implemented with a binary Dynamic HTML (DHTML) behavior. Element behaviors are encapsulated components, so they can add new and interesting functionality to a Web page while improving the organization of content, functionality, and style.

DHTML behaviors were introduced in Internet Explorer 5 and made it possible to modify the behavior of standard HTML elements by setting the behavior attribute of a Cascading Style Sheets (CSS) entry or by using the addBehavior method in script. DHTML behaviors, in the form introduced in Internet Explorer 5, are now referred to as attached behaviors, to distinguish them from element behaviors—which use a different binding mechanism and have other unique characteristics.

Element behaviors can be used to implement anything from a simple rollover effect to a complex interactive component. A special processing instruction is used to import an element behavior into a Web page, where it is synchronously bound to a custom element. Once an element behavior has been downloaded and parsed, it exists as a first-class element in the document hierarchy and remains permanently bound to the custom element. Element behaviors differ significantly from attached behaviors in this respect. An attached behavior binds asynchronously to an element and modifies its behavior, and it can be attached or removed programmatically.

Element behaviors bring several enhancements to the Behavior Component Model in Internet Explorer 5.5. They provide new features that complement the existing capabilities of attached behaviors and provide additional robustness and reliability. However, attached behaviors are not superseded by element behaviors and remain useful in many scenarios.

A special feature of element behaviors, called viewlink, enables a document tree to be encapsulated in an HTC file, separate from the content of the main Web page. This opens up another realm of possibilities that are covered separately in the ViewLink Overview.

An element behavior can be implemented with an HTC file or a binary DHTML behavior, and the techniques used in each approach are quite different. This article is focused on writing element behaviors with HTC files. For more information on writing a binary element behavior, see How to Create a Binary Element Behavior using ATL.

The following topics are discussed in this document.


This section defines the terminology used in this article.

attached behavior A DHTML behavior that binds asynchronously to standard HTML elements. It is possible to attach DHTML behaviors using the behavior attribute with CSS or by using the addBehavior method in script.
element behavior A feature of Internet Explorer 5.5 that allows DHTML behaviors to be bound synchronously to a custom element. Custom elements bound to element behaviors can be used like any other element in an HTML document, ensuring that the functionality of the behavior is never removed from the element.
viewlink A feature of element behaviors that enables the content in an HTC file to be displayed in a Web page.
primary document A Web page being browsed by the client.
document fragment One or more HTML elements that exist independent of the main body of content in the primary document. The viewlink feature, or other scripting methods such as appendChild, can be used to insert a document fragment into a primary document and render it.
custom element A user-defined element, also known as a custom tag. A namespace must be declared for an HTML document that uses a custom element.
master element A custom element that implements an element behavior with a viewlink. A viewlink enables the document fragment of an element behavior  to be rendered as the content in the primary document.
lightweight HTC An HTML component file that does not use or render its own static HTML content. This is used when possible, to maximize the efficiency of the component initialization and the speed of the Web page rendering.
namespace A collection of names that can be used by custom elements or attributes. A namespace is used to ensure that elements are uniquely qualified. For more information, see XML Tutorial: Using Namespaces.

This overview focuses on element behaviors that use an HTC file to implement a custom element. Therefore, wherever the term element behaviors is used in this overview, it does not refer to the implementation of a binary element behavior, unless otherwise stated.

Although an element behavior can be used to define a custom element, this is not the only use for custom elements; for example, an attached behavior can also be bound to a custom element.


You should be familiar with DHTML behaviors and the concepts behind HTC components. If you are new to DHTML behaviors, then the Introduction to DHTML Behaviors Overview and also the HTC Reference provide the necessary foundation for understanding element behaviors.


The primary benefit of element behaviors is that they enable the creation of custom elements, which can be used just like standard HTML elements in a Web page. Internet Explorer 5.5 is the first browser to enable HTC files to be used to define custom elements. attached behaviors overwrite the default behavior of the element to which they are attached, whereas element behaviors are used to define new elements. Since element behaviors are encapsulated in an HTC file, the implementation of a Web page that uses custom elements has better organization and the content of the primary document can be much less cluttered. DHTML behaviors defined with HTC files can be used in any page within the same domain, so element behaviors are an excellent way of creating powerful, reusable components.

Since an element behavior is bound synchronously, it means that the custom element is initialized as soon as it has been downloaded and parsed. The use of synchronous binding with element behaviors puts them on a par with regular HTML elements in terms of their robustness and reliability. The robustness of element behaviors is associated with the binding mechanism, but as with any component, the reliability and functionality of an element behavior is dependent on the quality of its implementation. An element behavior cannot be disconnected from a custom element using script or any other mechanism, which is a desirable feature in many applications of DHTML behaviors. Therefore, an element behavior should be regarded as a bona fide HTML element; once it has been parsed and initialized, it exists as a first–class element in the document tree.

Element behaviors with HTC files can be written to implement almost everything that is possible with binary DHTML behaviors. It is easier to implement an element behavior using an HTC file, since the functionality is written with script, this fact alone should bring relief to anyone who does not wish to learn Microsoft Visual C++ in order to write custom browser components. Also, your choice to build element behaviors with HTC files doesn't restrict the scope or functionality of the component significantly; the only scenarios that require a binary DHTML behavior are: when writing a Rendering Behavior or if the component needs to use Query Services.

Browser security issues are somewhat simplified when using HTC files to implement element behaviors, mainly because the client must provide permission before a binary component is downloaded to the browser. When an element behavior is implemented with a HTC file, it is automatically downloaded as a part of the Web page, the result is a browsing experience where the component download is invisible to the client. The implementation for HTC files in Windows Internet Explorer requires that the HTC file be located in the same domain as the primary document; otherwise, an access-denied error results.

Developing compelling interactive Web pages requires several skills, and writers, programmers, and designers routinely work together to develop a Web page. Traditional page authoring meant working with a single HTML document containing a mixture of scripting, content, and formatting. This situation arose from the popularity of the HTML document, but an HTML file hardly provides the ideal medium for a team to work together. The beauty of HTC files is that they help to encapsulate content, script, and style into discrete containers, enabling each specialist to concentrate on specific tasks.

The Behavior Component Model in Internet Explorer 5.5 brings many of the advantages of component–based development to the Web. It is now possible to build a powerful HTC file library where the code is easier to manage and less memory-intensive to maintain.

Creating a Custom Element

The following steps outline the basic process of creating and using a custom element in a Web page.

  • Define the element behavior in the HTC file.
  • Import the definition of the custom element in the primary document.

Implementing an element behavior with an HTC file is very similar to writing an attached behavior. The main difference is the implementation of the component in the primary document. With attached behaviors, the behavior is bound to the HTML element by setting the behavior attribute to the URL of the HTC file, whereas with element behaviors the binding is accomplished by creating a custom element.

Defining an Element Behavior

To define an element behavior, the main task is to write the HTC file. An HTC file uses a PUBLIC:COMPONENT element; this provides a container for other elements that define the component interface and set the default properties of the component. The HTC Reference provides information on all the elements that can be used inside the PUBLIC:COMPONENT element.

An element behavior uses the PUBLIC:COMPONENT tag to specify the name of the custom element with the tagName attribute. In the following example a checkers element is implemented.

<PUBLIC:COMPONENT tagName="checkers">

So far, this skeleton implementation of the checkers tag lacks attributes for setting the checkerboard's appearance, its play strength, or anything else. The attributes of a custom element can be defined by using the PUBLIC:PROPERTY element. The following sample adds an attribute, named boardWidth, to the checkers custom element:

<PUBLIC:COMPONENT tagName="checkers">
	<PUBLIC:PROPERTY NAME="boardWidth" />

A script function inside an HTC file can be made public to other components or to script in the primary document. In the following sample, a PUBLIC:METHOD element is added to the component; this uses the newGame function to start a new game of checkers. Also, an PUBLIC:ATTACH element is added to map the mouseover function to handle instances of the onmouseover event.

<PUBLIC:COMPONENT tagName="checkers">
	<PUBLIC:PROPERTY NAME="boardWidth" />
	<PUBLIC:METHOD name="newGame()" />
	<PUBLIC:ATTACH event="onmouseover" onevent="mouseover()" />

<SCRIPT Language="Javascript">
function newGame(){
// insert code to initialize a new game here

function mouseover(){
// insert code to handle mouseover events

To complete the behavior, elements would be added inside the PUBLIC:COMPONENT element to define the remaining methods, properties and event handlers for the checkers component. A completed checkers component would probably include the script for the checkers game as well. Once completed, the implementation of a game of checkers is completely encapsulated in the Checkers.htc file.

Note that the implementation of the checkers component contains no references to a namespace; the namespace is declared in the primary document, and this is explained in the next section. The same element behavior can actually be imported into multiple namespaces within a single primary document, and although this technique is not used in the sample, it can be useful with many other types of components.

As shown in the example, it is recommended that script blocks be placed after the PUBLIC:COMPONENT definition. Also, the script block should be placed either before the <BODY> tag or immediately before the </BODY> tag.

For more information about using the PUBLIC:COMPONENT tag with behaviors, see Using HTML Components to Implement DHTML Behaviors in Script.

Importing a Custom Element

The primary document requires a few simple additions to import the custom element. The HTML document first declares a namespace, which is used to ensure that the custom element has a unique qualifier. The following HTML element declares a namespace called games using the XMLNS attribute. Setting this attribute allows a custom element with the prefix "games" to be used in the primary document.

<HTML XMLNS:games>

The next step is to import the custom element into the namespace. In the following example, the games namespace imports the implementation of the checkers element in the Checkers.htc file.

<?IMPORT namespace="games" implementation="checkers.htc" >

The IMPORT directive is really the key to implementing an element behavior in the primary document. When the browser begins processing the IMPORT directive, it waits until the contents of the HTC file have downloaded completely before continuing. The way this instruction is processed is the reason why the behavior is bound synchronously to the custom element.

Finally, the custom element must be inserted somewhere in the body of the primary document. A custom element can be used like any other tag, except that the custom element uses its namespace as the prefix. The custom element for the checkers game could be defined as follows:


A simple custom element does not need to be defined as a block element, so in this case the following form can also be used.

<games:checkers />

If a custom element is used without a closing tag, as in the previous example, the last element attribute must be separated from the terminating /> characters, or the value of the attribute must be bounded by quotes. See Using Empty-Element Tags for more information.

The complete HTML file, which implements the checkers element, is shown below.

<HTML xmlns:games>
<?IMPORT namespace="games" implementation="checkers.htc" >
<games:checkers />

Now that the basic steps to create an element behavior have been covered, it's time to continue with a more functional example.

Creating a Rollover Tag

This example uses an element behavior to create a custom element that implements a rollover effect. Rollovers are typically text blocks that change their appearance when the mouse pointer hovers over them. They are used to provide visual feedback to indicate that the element can be clicked.

A better way to implement a simple rollover effect is to change the behavior of the a tag using an attached behavior, because a simple rollover effect does not really justify the creation of a custom element. Nevertheless, the example demonstrates some useful techniques that are readily used in more complex applications. For an example of how to use attached behaviors to implement rollovers, see Using DHTML Behaviors.

Creating the Rollover Component

The HTC file contains the implementation of the rollover tag. The tag has one property, called href, which is the hyperlink of the Web page to visit when the user clicks the rollover.

The rollover tag requires handlers for the following events:

  • onmouseover occurs when the mouse pointer moves over the rollover element. The event handler changes the text color to red, underlines it, and changes the cursor to a hand.
  • onmouseout occurs when the mouse pointer moves off the rollover. The event handler restores the text to its original state.
  • onclick occurs when the rollover is clicked. The event handler loads the Web page specified by the href property, if the property has been specified.

The following example shows how to create the HTC file for the rollover tag.

  1. Create the HTC file.

    Create a text file called rollover.htc and add the PUBLIC:COMPONENT tag.

    <PUBLIC:COMPONENT tagName="rollover">

    The PUBLIC:COMPONENT tag indicates that the HTC file contains the implementation of a tag named "rollover".

  2. Add the property definition.

    After the first line, add the property definition for href.


    This example defines the href property as an attribute of the rollover tag.

  3. Create event handlers.

    Attach handlers to three different events associated with the rollover tag.

    <PUBLIC:ATTACH EVENT="onmouseover" FOR="element" ONEVENT="Hilite()" />
    <PUBLIC:ATTACH EVENT="onmouseout" FOR="element" ONEVENT="UnHilite()" />
    <PUBLIC:ATTACH EVENT="onclick" FOR="element" ONEVENT="GotoLink()" />

    This example attaches events to the rollover element, as follows:

    • onmouseover fires Hilite()
    • onmouseout fires UnHilite()
    • onclick fires GotoLink()
  4. Write the event handler scripts.

    Add the script tag after the PUBLIC:COMPONENT, to enclose the script and event handlers.


    Between the script tags, add the definitions for each event handler and any other script that is necessary to implement the features in the behavior. For the Hilite event handler, use:

    function Hilite()
    	normalColor = element.style.color;
    	normalDecoration = style.textDecoration;
    	element.style.color = "red";
    	element.style.cursor = "hand";
    	element.style.textDecoration = "underline";

    The Hilite event handler saves the color and text decoration of the text contained within the rollover tags, sets the color to red, sets the cursor to a hand (indicating a hyperlink), and sets the decoration to underline.

    For the UnHilite event handler, use:

    function UnHilite()
    	element.style.color = normalColor;
    	element.style.textDecoration = normalDecoration;
    	element.style.cursor = "";

    This event handler restores the color and text decoration of the text within the rollover tag to the saved values in the Hilite event handler.

    Finally, for the GotoLink event handler, use:

    function GotoLink()

    This event handler checks to see if the href property is defined; if it is, it navigates to the URL specified by the href property.

The implementation of the rollover tag is ready for use in the primary document.

Creating the Rollover Custom Tag

This section shows how to implement the rollover custom element.

  1. Create the HTML file.

    Create an HTML file and declare the namespace that it uses at the top of the file. This example uses a namespace called addon. The name of the namespace is not important as long as one is declared.

  2. Declare the namespace.

    To declare your namespace, use:

    <HTML xmlns:addon>
  3. Import the implementation of the tag.

    Import the tag's implementation, by adding the following instruction after the <HTML> element:

    <?IMPORT namespace="addon" implementation="rollover.htc" >

    The import tag is a Processing Instruction, or PI, and uses <? to start the tag instead of the < character, as with regular HTML elements.

  4. Add the new custom element.

    The custom element can now be used. For example:

    <addon:rollover href="http://www.microsoft.com">Visit the Microsoft Web Site</addon:rollover>

When the mouse pointer moves over the rollover tag, the text contained within the tag changes to red, it is underlined, and the cursor changes to a hand. When the mouse pointer moves outside the rollover tag, the cursor changes back to an arrow and the text returns to its original state. If the user clicks the text within the rollover tag and the href attribute is defined, the URL specified by the href attribute is loaded.

Inline vs. Block Elements

By default, element behaviors render as inline elements in the primary document. To render an element behavior as a block element, you must set the element's display style to "block".

The element behavior in this sample HTC file renders as an inline element. Script in the sample sets the display style of the master element to "block" when the element is clicked.

   <PUBLIC:ATTACH EVENT="onclick" ONEVENT="makeBlock()" />

   //The element behavior renders as an inline element by default.
   element.innerHTML = "*Element behavior: Click me if you dare.";
   element.style.cursor = "hand";
   element.style.backgroundColor = "orange";

   function makeBlock() {
	  element.innerHTML = "Element behavior: Lions and tigers and bears.";
      //Setting the element's style to 'block' renders it as a block element
      //in the primary page.
	  element.style.display = "block";



This sample primary document contains the document fragment.


<BASEFONT FACE="Verdana" SIZE="4" />
   <DIV STYLE="background-color: green; color: white;">
      Containing page: The tortoise and the hare. </DIV>
   <ELEMENT:animals />
   <DIV STYLE="font-size: x-small">
      <P>*Click the element behavior to change it into a block element.</P>

Code example: http://samples.msdn.microsoft.com/workshop/samples/author/behaviors/overview/animals2.htm

Lightweight HTC Files

Internet Explorer creates a separate document tree for each use of an element behavior in the primary document. As an HTC file is actually an HTML document, a document tree is built for its contents when it is parsed. When a large number of element behaviors are assembled in a single page, the result is a slow page load.

It is often possible to write an HTC file that does not contain any static HTML; when it is possible to do this, the new "lightweight" attribute of the PUBLIC:COMPONENT element can be used so that the HTC file is handled in the most efficient manner. With a lightweight HTC unnecessary parsing, and the creation of empty document trees, is eliminated. Therefore, the result of using a lightweight HTC is that the page loads much faster, especially when multiple instances of the same custom element are used.

If a component contains a document fragment and uses viewlink to render it in the primary document, then the HTC file is processed efficiently. In many applications of HTC files a behavior does not require a viewlink to render content, or there simply might not be any content to render; in this situation, an unnecessary memory usage results, which can be remedied by specifying a lightweight component.

Therefore, when it is possible for a component to be implemented without its own document tree, a lightweight component should be implemented by specifying the new "lightweight" attribute on the PUBLIC:COMPONENT element, as shown in this example:

<PUBLIC:COMPONENT tagName="rollover" lightweight = true >

A lightweight HTC file supports only the following tags.


Because the example rollover tag does not use HTML in the HTC file and because it could be used many times in a typical Web page, it would be a good application of a lightweight element behaviors. The checkers custom element could also be implemented as a lightweight HTC file.

Even though lightweight HTC files do not have a document structure of their own, and therefore have no document to reference, lightweight HTC files can actually contain static HTML; but if they do the content will be ignored. Script in the HTC file can use the createElement method to add content in the primary document by using the following syntax: element.document.createElement.

As the <?IMPORT> processing instruction can be used in a lightweight HTC file, it is possible to nest HTC files.

Literal Content

The contents between the opening and closing tags of the custom element can serve many purposes if it is marked as Literal Content instead of being parsed and rendered. The component author can use the custom element content, manipulate it, or parse it in whatever way is necessary to implement a component. When a Literal Content component is defined, the custom element innerHTML is not parsed and added to the document tree—but it is accessible using script. Two examples of commonly used Literal Content elements in HTML documents are the <SCRIPT> and <XML> tags.

A Literal Content element behavior would be specified by using the "literalContent" attribute on the PUBLIC:COMPONENT element:

<PUBLIC:COMPONENT tagName="myTag" literalcontent=true >

The innerText property is not available for a custom element that is implemented with a Literal Content element behavior. If an attempt is made to set the innerText property of the custom element an error occurs. If the innerText property of a Literal Content element behaviors is retrieved in script, it returns as null.

The innerHTML property can be used to set and retrieve the custom element Literal Content. The innerHTML property of the custom element is available once the oncontentready event has fired. Therefore, an event handler should be attached to this event in a Literal Content component that retrieves the innerHTML property of the custom element. Otherwise, an error occurs, which indicates that the innerHTML property is not yet available.

The oncontentsave event is fired during a save, copy, get innerText, get innerHTML, or drag-and-drop operation. So this event can be useful when writing a Literal Content element behavior.

An XML data island is a good example of Literal Content. For more information, see XML Data Islands.

The defaults Object

The defaults object is used to set and retrieve the default properties for HTC files. This object also has a declarative form, the PUBLIC:DEFAULTS element, which is used in the component definition section of an HTC to set the initial state of the behaviors properties.

A viewlink is established for an element behavior when the viewLink property is set to an object containing document content. When the viewlink is set, the value of the viewLink property refers to the document fragment. By default, the viewLink property has the default value of null, meaning that there is no document fragment. For more information, see the ViewLink Overview.

The PUBLIC:DEFAULTS element has several attributes that correspond to the collection of properties of the defaults object; so you can use either script or declarations to set properties.

The following sample shows how the PUBLIC:DEFAULTS element can be used to set the default CSS style properties for an element behavior:

<PUBLIC:COMPONENT tagName="myTag">
<public:defaults style="font-Weight:bold;font-Style:italic" tabStop = "true" >

The tabStop property is also set to true in this sample, which means that the element behavior can receive focus and participate in the tabbing sequence.

Accessing the Content of Custom Elements

To access the content of a custom element, use the element object. Script in the HTC file can access and change the contents of the custom element by reference to the element object.

element.style.color = "red";

The preceding example changes the color of the text contained within the tag to red.

The primary document tree can be accessed within the component script using the following syntax:


If the document object is used on its own, it refers to the HTC file's document object.

Component Initialization

An element behavior binds synchronously to a custom element. Therefore, it is not necessary to add event handling functions to check to see if the component has been downloaded and parsed. The component will have been parsed by the time scripting in the component executes.

Inline script within an HTC file executes as soon as the browser can run it, so any initialization in this portion of the script should only apply to items that are independent of the status of the custom element or of any contents in the primary document.

When the oncontentready notification fires, the content of the custom element has been successfully parsed and built. An HTC file should attach a function to this event if it is to set any properties that apply to the custom element or its contents. Also, oncontentready is the correct event to use to initialize a viewlink element behavior in script.

When the ondocumentready event fires, the document has been completely parsed and built. Initialization code should be placed here if the component needs to navigate the primary document structure. The ondocumentready event notifies the component that the entire page is loaded, and it fires immediately before the onload event fires in the primary document.

A few methods, such as doScroll, require the primary document to be completely loaded. If these methods are part of an initialization function, they should be handled when the ondocumentready event fires.

Binary Behaviors

Element behaviors can also be implemented with binary DHTML behaviors, which would typically be written with a language such as Visual C++. In this section the use of a binary DHTML behaviors in an Web page is illustrated, but the process of writing the binary behavior is outside the scope of this article. For information on using or writing a binary behavior, see Implementing Binary DHTML Behaviors.

The following code sample illustrates the basic approach to importing a binary DHTML behavior in the primary document.

<html xmlns:mybb>
<object id=mytag ... ></object>
<?import namespace=mybb implementation=#mytag >

The sample contains the object element in the <HEAD> section, which is recommended for binary DHTML behaviors. The id attribute has the value mytag and the remaining attributes for the element are not shown for simplicity. The binary behavior is imported using a similar approach to the method used for HTC files; except that the implementation attribute is set to #mytag, instead of the URL of an HTC file, which references the object elements id.

The IMPORT processing instruction can appear anywhere in an HTML file, but when implementing a binary behavior, it is important to place the object tag before the IMPORT. Another reason why the object tag is in the head section is that the object tag does not render any content for a binary DHTML behaviors; therefore, it doesn't belong in the body. Any object tag that is not in the document body is implied to be in the head of the document. The IMPORT processing instruction is not an HTML element, it does not render in the primary document, and it is not a part of the document tree.

Download Permissions

The content in an HTC is considered to be a part of the primary document, so HTC files are downloaded automatically to the browser; they do not require any user permission prior to downloading. One requirement for an HTC file is that it must be downloaded from a URL within the same domain as the primary document, otherwise an access denied error results. For more information on component download issues, see the HTC Reference and Introduction to DHTML Behaviors articles.

Binary components differ from HTC files with respect to security and are basically handled the same way as Microsoft ActiveX components. Generally, they require user permission prior to download, unless specific security settings have been defined for the site containing the primary document.

Preventing Printing Problems

If an element behavior modifies the element tree of the primary document through script, the content of the element behavior could appear twice when the page is printed. Also, the script contained in the HTC file might execute again when the user previews or prints the page. By enclosing the script that modifies the element tree with the following conditional statement, you can avoid the printing problem.

if(document.media != "print") {

// script that modifies the element tree goes here

Using Empty-Element Tags

When you use an empty-element tag such as <a:b/>, the terminating /> characters can be misinterpreted as being part of an attribute's value. The following table shows valid ways to define attributes with empty-element tags so that they are parsed correctly.

TagInternet ExplorerRemarks
<a:b value=c/>IllegalInternet Explorer cannot determine if the tag has closed, so it scans for a closing tag of </a:b>.
<a:b value=c />LegalThe space after c terminates the value attribute.
<a:b value="c"/>LegalThe quote after c terminates the value attribute.

Related Topics

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

© 2014 Microsoft. All rights reserved.