Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Change handlers on-the-fly

Event Handling

Change handlers on-the-fly

by  baad  Posted    (Edited  )
I see this kind of questions on these forums pretty often :
~how 2 add something to ... event handler
or
~how 2 remove some handler
áááááááááááááááááááá
i'll talk about onclick handler, but it could be any of them..
& another thing: this code works in ie only (at least onclick is not supported by nc4)

0. have a look at my faq about enabling/disabling "readonly" attribute of form fields: faq216-795 but there i just removed handler with
[color green]handler=new Function()[/color]

1. To remove defined handler just write
[color green]onclick=null[/color] or like i did it in the pointed faq

2. a bit harder: How to add to/remove something from event handler:

just copy-paste this code & play with it
[color green]
<html>
<head>
<title>changing function code</title>
<script>
[color gray]
/*********************
the main monster: this function gets handler's body
*********************/
[/color]
function getFuncBody(funcPtr) {
[color gray]//handler's body[/color]
var str=funcPtr.toString();
[color gray]// removes everything including first "{" (e.g. function name(){)[/color]
str=str.replace(/[^{]+{/,"");
[color gray]// removes last }[/color]
str=str.substring(0,str.length-1);
[color gray]// guess what :))[/color]
return str;
}

[color gray]//onclick handler:[/color]
function clicker(){
one();one()
one()
}

[color gray]//function that is used in onclick handler:[/color]
function one() {
var ii=0
if (!ii){alert('one')}
}

[color gray]
/*********************
function wich adds to current handler some actions: this time it is just alert('two') but u can call some other function.. play around
*********************/
[/color]
function doIt() {
document.onclick=new Function(
getFuncBody(document.onclick)+";alert('two')" );
}



[color gray]
/*********************
function wich removes all 'one()' function calls, but u can do whatever u whant
*********************/
[/color]
function doItagain() {
var str=getFuncBody(document.onclick)
str=str.replace(/one\(\)/g,';') //removal
document.onclick=new Function(str);
}

[color gray]//setting onclick event handler[/color]
document.onclick= clicker;
</script>
</head>
<body bgcolor="#FFFFFF">
<input type=button onclick="doIt()" value=add><br>
<input type=button onclick="doItagain()" value=remove><br>
</body>
</html>
[/color]

check out this thread to see the brainStorm: thread216-128339
well, looks good :)
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top