PRB: Setting JScript Event Handler Invokes the Handler Function (183509)



The information in this article applies to:

  • Microsoft Internet Explorer (Programming) 4.0
  • Microsoft Internet Explorer (Programming) 4.01

This article was previously published under Q183509

SYMPTOMS

Setting an event handler function with the following syntax causes the event handler function to be invoked.
div1.onclick = OnClickHandler(str);
				

RESOLUTION

Create a function object that calls your event handler like this:
div1.onclick = new Function("return OnClickHandler(str)");
				

STATUS

This behavior is by design.

MORE INFORMATION

When creating a Web page, you may want to associate an event handler with some object, such as a DIV tag. Associating the event handler by setting the event equal to the event handler function, causes the handler function to be invoked.

The following code fragment demonstrates the perceived problem and provides the solution:
<HTML>
<HEAD>
   <SCRIPT>
      function InitPage()
      {
         str = "Hello, world";

      // This causes the OnClickHandler to be called (Perceived Problem)
         div1.onclick = OnClickHandler(str);

      // This associates an event handler with an object (Solution)
         // div1.onclick = new Function("return OnClickHandler(str)");
      }

      function OnClickHandler(str)
      {
         alert(str);
      }
   </SCRIPT>
</HEAD>

<BODY onload="InitPage()">
   <P>Click the image to see the problem

   <DIV ID=div1 STYLE="position:relative; height:100; width:100;
                       background-color:red">
   </DIV>
</BODY>
</HTML>
				

REFERENCES

For more information about developing Web-based solutions for Microsoft Internet Explorer, visit the following Microsoft Web sites:

Modification Type:MajorLast Reviewed:5/11/2006
Keywords:kbcode kbprb KB183509