Peter wrote:
I would like to use code like the following:
this.onclick = function(e)
{
alert("I'm in the onclick handler");
}
But I do not want to wipe out any existing onclick event code. I want
to do this dynamically.
I tried variations like this:
var oc = this.onclick;
this.onclick = function(e)
{
alert("I'm in the onclick handler");
if (oc != null)
eval(oc.toString());
}
but can't get it to work.
Is this sort of thing possible? If so, how is it done?
TIA.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script type="text/javascript">
function addHandler(obj, evt, newhandler, captures)
{
if (obj.attachEvent)
obj.attachEvent('on' + evt, newhandler);
else if (obj.addEventListener)
obj.addEventListener(evt, newhandler, captures);
else
{
var oldhandler;
if (oldhandler = obj['on' + evt])
obj['on' + evt] = function()
{
oldhandler();
newhandler();
}
else obj['on' + evt] = newhandler;
}
}
function test()
{
alert('new handler...');
}
window.onload = function()
{
addHandler(document.getElementById('foo1'), 'click', test, false);
addHandler(document.getElementById('foo2'), 'click', test, false);
}
</script>
</head>
<body>
<button id="foo1">no old handler, new added onload</button>
<button id="foo2" onclick="alert('old handler...')">old handler, new
added onload</button>
</body>
</html>