Microsoft KB Archive/183509

= PRB: Setting JScript Event Handler Invokes the Handler Function =

Article ID: 183509

Article Last Modified on 5/11/2006

-

APPLIES TO


 * Microsoft Internet Explorer 4.0 128-Bit Edition
 * Microsoft Internet Explorer 4.01 Service Pack 2

-



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:    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); }   

 Click the image to see the problem

   

<div class="references_section">