HOWTO: Change the Function an Event Handler Points To

ID: Q190247


The information in this article applies to:
  • Microsoft JScript, versions 1.0, 2.0, 3.0
  • Microsoft Internet Explorer (Programming) version 5.0


SUMMARY

Sometimes you may want to change the code that an event handler is pointing to. To do this the function that the event handler points to must change. VBScript does not support this, but JScript does.


MORE INFORMATION

In the following example, the next time this button is pressed, you want to invoke this function with a different value for arguments. This function should get called with the value "value 2." The following code demonstrates two intuitive but incorrect methods of doing this. The two methods are commented.


<HTML>
<HEAD>
<TITLE>Changing event handlers at run-time</TITLE>
<script language="JScript">
<!--
function test (sArgs)
{
    alert ("I am test ()" + sArgs);

    // this actually calls the function,
    // which doesn't change it
    // and causes recursion.
    // btn1.onclick = test ('value 2')

    // this just changes the onclick
    // value to a new string,
    // but doesn't change the function.
    // btn1.onclick = "test ('value 2')"

}
-->
</script>
</HEAD>
<BODY>
<input id=btn1 type=button value="(JScript)Change function"
  onClick="test('value 1');">
</BODY>
</HTML> 

The following three lines build a string for use with the Function object in JScript and will change the handler function that onClick points to. Replace the two commented statements above with these three statements to correctly change the handler function.

   var newHandlerArg = "value 2" ;
   var newFunctionBody = "test('" + newHandlerArg + "');" ;
   btn1.onclick = new Function(newFunctionBody); 


REFERENCES

For further reference material on JScript, see the following Web page:

http://msdn.microsoft.com/scripting/

Additional query words: function pointer handler changing modifying dynamic

Keywords : kbcode kbAccess200fix kbJScript100 kbJScript200 kbJScript300 kbVBScript kbIE500
Version : WINDOWS:1.0,2.0,3.0
Platform : WINDOWS
Issue type : kbhowto


Last Reviewed: May 4, 1999
© 2000 Microsoft Corporation. All rights reserved. Terms of Use.