Element.addBehavior() (Method)

Attach a behavior to an object in MSIE.

Availability:

JScript - 5.0
Internet Explorer - 5.0
JavaScript syntax:IEmyElement.addBehavior()

MSIE supports an extension to style sheet handling that provides for scripts to be called as part of the style. These are called behaviors. The script source text is stored in a special and separate file with an .htc (or .HTC) file extension. It stands for HTml Component.

This augments the already available event handler support which provides for handlers to be registered with individual objects or with a particular instance of a tag. Behaviors allow a handler to be registered with all occurrences of a tag with only one registration being necessary.

Here is the contents of a simple HTC file taken from the Wrox book Professional JavaScript.

   <SCRIPT LANGUAGE="JScript">
   attachEvent("onclick", event_onclick);
   function event_onclick()
   {
      alert("Read the manual.");
   }
   </SCRIPT>

This can be defined in a style sheet or in a <STYLE> tag. Here is how it would be invoked with an inline <STYLE> defined in the <HEAD> of a document:

   <STYLE>
      .help{behavior:url(help.htc)}
   </STYLE>

Having defined the style, you can now apply this to any element. For example, it could apply to the entire contents of a <DIV> block like this:

<DIV CLASS="help" DELAY="2000">Click for help</DIV>

The DELAY HTML tag attribute provides a way to delay the presentation of the <DIV> block contents until the browser has had a chance to load the HTC file content.

There are more complex ways to use behaviors that involve the use of XML mark-up and which can avoid the use of attachEvent() methods. Refer to the Microsoft web site for further details.

See also:.htc, Behavior, Element.removeBehavior()

Web-references:

http://msdn.microsoft.com/workshop/essentials/versions/IE5behave.asp