Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

How to add to existing onclick?

10 views
Skip to first unread message

Peter

unread,
May 13, 2005, 1:37:16 PM5/13/05
to
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.


RobB

unread,
May 13, 2005, 2:13:45 PM5/13/05
to

<!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>

Peter

unread,
May 13, 2005, 2:29:29 PM5/13/05
to
Rob,

Thanks. That's an interesting example.

In my testing, I was missing the parens after the name of the variable I was
storing the old handler in.

Much appreciated,
Pete

0 new messages