Removing an anonymous event listener

C

Csaba Gabor

Is there a way to remove an anonymous event handler that I attached
using attachEventListener? Or to say it another way, is there a way to
remove all event handlers that have been attached to an element?

Consider the html / script below. After attaching the onClick handler
to the div, I'd like to remove it. Perhaps there is a way to query the
div for all its handlers?

Thanks,
Csaba Gabor from Vienna

<div id=testdiv style="border:1px solid blue">Click me</div>
<script type='text/javascript'>
var div=document.getElementById('testdiv');
div.addEventListener("click",
function() {alert("I've been clicked")}, false);
div.removeEventListener("click", div.onClick, false);
</script>
 
S

sneill

You can also attach events like this:

div.onclick = function() { ... }

and remove them like this:

div.onclick = null;
 
M

Michael Winter

Is there a way to remove an anonymous event handler that I attached
using attachEventListener?

If you didn't maintain a reference to the function object, then no. You
must be able to a pass a reference to the removal method in order for
the method to find and remove that listener.
Or to say it another way, is there a way to remove all event handlers
that have been attached to an element?
No.

[snip]

Perhaps there is a way to query the div for all its handlers?

No, there isn't.

[snip]

Mike
 
M

Martin Honnen

Csaba said:
Is there a way to remove an anonymous event handler that I attached
using attachEventListener? Or to say it another way, is there a way to
remove all event handlers that have been attached to an element?
var div=document.getElementById('testdiv');
div.addEventListener("click",
function() {alert("I've been clicked")}, false);

No, that way with DOM Level 2 at least there is no way to remove that
event handler, you would need to store the function somewhere to be able
to pass it later to removeEventListener.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,190
Latest member
ClayE7480

Latest Threads

Top