PRB: Setting JScript Event Handler Invokes the Handler Function

ID: Q183509


The information in this article applies to:


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, please see the MSDN Web Workshop:

http://msdn.microsoft.com/workshop/default.asp

Additional query words:


Keywords          : kbcode kbIE400 kbIE401 kbIE500 
Version           : WINDOWS:4.0,4.01
Platform          : WINDOWS 
Issue type        : kbprb 

Last Reviewed: April 30, 1999