Click to return to the DHTML, HTML     
DHTML Behaviors     Implementing DHTML Behavi...     DHTML, HTML & CSS    
Web Workshop  |  DHTML, HTML & CSS

Using DHTML Behaviors


Applying a behavior to an element is as easy as attaching a style to an element on a page. This article covers the different approaches and considerations to applying a behavior to standard HTML elements. In addition, it presents some interesting applications of behaviors in Microsoft® Internet Explorer 5 and later. After reading the article, you'll be able to start applying behaviors to your own pages, isolate script from your content, and take advantage of the resulting cleaner pages.

If you've authored a page using cascading style sheets (CSS), most of the information in this article should be familiar to you. If you are new to CSS, the Related Topics section includes links to CSS articles that provide background information.

Implementing behaviors is also beyond the scope of this article and is discussed in a few separate articles listed in the Related Topics section.

Applying a Behavior to an Element

Internet Explorer provides two ways to apply a behavior to an element.

  1. Through scripting, using the addBehavior method.
  2. The addBehavior method is the dynamic way of applying a behavior to an element. When the method is called, the behavior is appended to a list of behaviors being applied to the element (as opposed to overwriting the behavior that might have already been attached to that element at the time the method was called). Once attached, the behavior can be detached anytime using the removeBehavior method.

    The following example demonstrates how a behavior that implements a mouseover highlighting effect could be dynamically attached to all LI elements on a page using addBehavior, and then subsequently detached using removeBehavior.

    Sample Code

    <SCRIPT LANGUAGE="JScript">
    var collBehaviorID = new Array();
    var collLI = new Array ();
    var countLI = 0;
    
    function attachBehavior()
    {
       collLI = document.all.tags ("LI");
       countLI = collLI.length;
        for (i=0; i < countLI; i++)
    {
       var iID = collLI[i].addBehavior ("hilite.htc");
       
       // if behavior has already been added to the element, 
       // addBehavior returns 0.
           if (iID)   
              collBehaviorID[i] = iID
      } 
    }
    
    </SCRIPT>
    
    :
    Click <A HREF="javascript:attachBehavior()">here</A> 
    to add a highlighting effect as you hover over each item below.
    :
    
    This feature requires Microsoft® Internet Explorer 5 or later. Click the icon below to install the latest version. Then reload this page to view the sample.
    Microsoft Internet Explorer

  3. Through CSS, using the proposed new CSS behavior attribute.
  4. If you've ever used CSS to change the style of an element, then you already know how to apply a behavior to an element on a page using the proposed new behavior attribute.

    Note When using the behavior attribute, it is important to know the type of behavior you are trying to use—a behavior implemented as a binary component (using C++ or any compiled code), as a default behavior (built in to Internet Explorer), or as a component written in script (either as an HTML Component or as a scriptlet). The type of behavior determines the syntax used to apply the behavior to an element using CSS. More information about the correct syntax for using the behavior attribute on an element is available at the behavior attribute reference page.

    As a proposed CSS attribute, the behavior attribute can be specified on an element just like any CSS attribute, as follows:

    1. By defining an inline style.
    2. <UL>
        <LI STYLE="behavior:url(hilite.htc)">HTML Authoring
        <LI STYLE="behavior:url(hilite.htc)">Dynamic HTML</LI>
      </UL>
      This feature requires Internet Explorer 5 or later. Click the icon below to install the latest version. Then reload this page to view the sample.
      Microsoft Internet Explorer

    3. By defining an embedded style, using the HTML element as a selector. This example causes all instances of the anchor element, A, to behave as defined in hilite.htc.
    4.    <HEAD>
         <STYLE>
            LI { behavior:url(hilite.htc) }
         </STYLE>   
         </HEAD>
      
      <UL>
        <LI>HTML Authoring</LI>
        <LI>Dynamic HTML</LI>
      </UL>
      This feature requires Internet Explorer 5 or later. Click the icon below to install the latest version. Then reload this page to view the sample.
      Microsoft Internet Explorer

    5. By defining an embedded style, using a class name as a selector. Note that the selector begins with a period (.), which is the required syntax for class names as selectors. This will cause every element assigned the class name of HILITE to behave as defined in hilite.htc.
    6.    <HEAD>
         <STYLE>
            .HILITE { behavior:url(hilite.htc) }
         </STYLE>   
         </HEAD>
      
      <UL>
        <LI CLASS="HILITE">HTML Authoring</LI>
        <LI CLASS="HILITE">Dynamic HTML</LI>
      </UL>
      This feature requires Internet Explorer 5 or later. Click the icon below to install the latest version. Then reload this page to view the sample.
      Microsoft Internet Explorer

    7. By setting the style subobject of the element through script, as in the folling example:.
    8.    <HEAD>
         <SCRIPT>
         function window.onload()
         {
            L1.style.behavior = "url(hilite.htc)";
            L2.style.behavior = "url(hilite.htc)";
         }
         </SCRIPT>
         </HEAD>
      
      <UL>
        <LI ID=L1>HTML Authoring</LI>
        <LI ID=L2>Dynamic HTML</LI>
      </UL>
      This feature requires Internet Explorer 5 or later. Click the icon below to install the latest version. Then reload this page to view the sample.
      Microsoft Internet Explorer

    How you choose to specify the behavior attribute depends largely on how many elements you want to apply the behavior to. Defining the behavior inline or through script is best when you want to apply it to a select number of elements. Defining an embedded style is best for applying the behavior to a set of elements globally.

    Note A behavior attached to an element through CSS, using a style rule defined in the document, is automatically detached from the element as soon as the element is removed from the document tree. Once the element is removed, all associations of that element to any element in the document tree, such as style sheet rules that specify behaviors, are stripped from the element as well. On the other hand, a behavior attached to an element through an inline style, or through the addBehavior method, is not automatically detached from the element when the element is removed from the document hierarchy. These two methods of applying behaviors have no dependencies on the containing document, and therefore the behavior remains applied to the element even as it is removed from the document tree. The removeBehavior method can be invoked to explicitly detach this type of behavior from the element.

Applying Multiple Behaviors to an Element

Multiple behaviors can be applied to an element by specifying a space-delimited list of URLs for the behavior attribute, as shown in the following code. This particular sample demonstrates how two behaviors can be applied to an element to achieve a combination of effects.

<UL>
  <LI STYLE="behavior:url(collapsing.htc) url(hilite.htc)">HTML</LI>
  <UL>
      <LI>IE 4.0 authoring tips</LI>
  :
  </UL>
</UL>
This feature requires Internet Explorer 5 or later. Click the icon below to install the latest version. Then reload this page to view the sample.
Microsoft Internet Explorer

Note The addBehavior method can also be called to apply additional behaviors to an element.

Resolving Conflicts

When applying multiple behaviors to an element, conflicts are resolved based on the order in which the behavior was applied to the element. From the example above, this means that the collapsing.htc behavior is applied first, followed by the hilite.htc behavior with each behavior taking precedence over the previous one. In this example, there were no conflicting style assignments between the two behaviors, so all style changes made by both behaviors were applied unaltered to the element. If, however, both behaviors set the element's color, the hiliting behavior's color prevails, as it was applied to the element last. The same rule applies when resolving name conflicts, such as with property, method, or event names exposed by multiple behaviors.

Despite the support provided for multiple behaviors, it is interesting to note that the behavior property of an element, just like the color property, can be overridden when multiple styles are applied to an element. In the following example, both the Collapsing class and the inline style for the LI element define the behavior attribute. When resolving style conflicts in an HTML document, the CSS rules of cascading and inheritance prevail. In this case, the inline style takes precedence over the rule with CLASS as the selector. According to CSS rules, the order of specificity, from greatest to least, is: (1) inline styles; (2) ID; (3) CLASS; and (4) HTML element. Applying that rule to the example, the inline style that applies the highlighting behavior to the element prevails over the Collapsing class, so that only the highlighting effect gets applied to the LI; the expanding/collapsing effect does not get applied.

<STYLE>
   UL  { font-family: verdana, arial, helvetica, sans-serif; font-size:10}
   .Collapsing {behavior:url(collapsing.htc) }
</STYLE>
:
<UL>
   <LI CLASS="Collapsing" STYLE="behavior:url(hilite.htc)">HTML Authoring</LI>
   :
> 
This feature requires Internet Explorer 5 or later. Click the icon below to install the latest version. Then reload this page to view the sample.
Microsoft Internet Explorer

Accessing the Behavior's Object Model

As a component, a DHTML behavior may expose properties, methods, and events that define its object model. When a behavior is applied to an element, the element's properties, methods, and events are extended to include those exposed by the behavior.

Using Properties

Behavior properties can be specified inline on the element, the same way HTML attributes are specified, or through script.

For example, consider a behavior that implements displaying and hiding content. This behavior can be applied to an element, which when clicked, toggles the visibility of the elements underneath it. The behavior could expose a CHILD property to specify the element to be shown or hidden. The following example demonstrates how this behavior can be applied to a table of contents, and how a behavior's property can be specified inline.

<HEAD>
<style>
   .CollapsingAndHiliting {behavior:url(ul.htc),url(hilite.htc)}
</style>
</HEAD>

<UL>
  <LI CLASS="CollapsingAndHiliting" CHILD="Topics1">HTML Authoring</LI>
  <UL ID="Topics1">
      <LI><A HREF="">Internet Explorer 4.0 authoring tips</A></LI>
      <LI><A HREF="">Four special effects with Internet Explorer 4.0</A></LI> 
  :
  </UL>
  <LI CLASS="CollapsingAndHiliting" CHILD=Topics2>Dynamic HTML (DHTML)</LI>
  <UL ID=Topics2>
      <LI><A HREF="">Overview</A></LI>
      <LI><A HREF="">Technology comparison</A></LI>
  :
  </UL>
</UL>
   
This feature requires Internet Explorer 5 or later. Click the icon below to install the latest version. Then reload this page to view the sample.
Microsoft Internet Explorer

Calling Methods

The following example demonstrates how a behavior's method can be called from a containing page. The behavior in this example implements the effect of flying across a page and exposes a tick() method.

<HEAD>
<STYLE>
   .FLY  {behavior:url(fly.htc)}
</STYLE>
</HEAD>
     
<BODY onload="window.setInterval (oTitle.tick(), 1000)">
<H1 CLASS=FLY ID=oTitle>I Believe I Can Fly</H1>
:
</BODY>

Handling Events

Events fired by behaviors are handled the same way as standard DHTML events. For more information on the various ways to handle events in Internet Explorer, refer to the article, Understanding the Event Model.

The following example defines two event handlers, fnSaveInput() and fnLoadInput(), to handle the onload and onsave events respectively. The example applies the saveFavorite behavior to an INPUT element. This causes the contents of the INPUT element to be saved when the page is added as a favorite.

For more information on persistence in Internet Explorer 5, see Persistence Overview.

<HEAD>
<STYLE>
   .saveFavorite {behavior:url(#default#savefavorite)}
</STYLE>
<SCRIPT>
   function fnSaveInput(){
      alert("The onsave event fired.");
      oPersistInput.setAttribute("sPersistValue",oPersistInput.value);
   }
   function fnLoadInput(){
      oPersistInput.value=oPersistInput.getAttribute("sPersistValue");
   }
</SCRIPT>
</HEAD>
<BODY>
<INPUT class=saveFavorite onsave="fnSaveInput()" onload="fnLoadInput()" 
   type=text id=oPersistInput>
</BODY>
      
This feature requires Internet Explorer 5 or later. Click the icon below to install the latest version. Then reload this page to view the sample.
Microsoft Internet Explorer

Related Topics

The following links are to other articles on the topic of DHTML Behaviors.



Back to topBack to top

Did you find this topic useful? Suggestions for other topics? Write us!

© 1999 Microsoft Corporation. All rights reserved. Terms of use.