3

Say I have the following jQuery:

$('#myelement').bind('click', foo);

How can I unbind this event without using jQuery?

The event doesn't show up in any of these methods on a DOM element:

var domElement = document.getElementById('myelement');
domElement.onclick // == null
domElement.click // == undefined

So how can I unbind it without using jQuery such as the following?

$('#myelement').unbind()
1
  • Purely out of curiosity, why do you want to do that? Commented Oct 9, 2010 at 22:03

1 Answer 1

2

If you're using a recent version of jQuery, this will work:

delete $.cache[document.getElementById("myelement")[$.expando]].events.click;

You can test it here.

Note that it's not a complete cleanup, you can use jQuery's .removeEvent() implementation for that, if you want to clear all handlers.

Sign up to request clarification or add additional context in comments.

8 Comments

Imagine a world without jQuery... :)
This works. Isn't it better to use the jQuery variable instead of $ though? Also, isn't there a way to disable jQuery's hook into the events of an element?
@Senseful - Either variable works, I used $ for brevity, use jQuery to be safe :) For the second question...I'm not sure what you're asking, you want to prevent it binding in the first place?
Note that this approach is using jQuery. If you're going to "use" jQuery anyway, why not just unbind the handler with the direct API? It's just going to do what this suggests anyway.
@Pointy - There's no way to not use the actual jQuery object, since the handlers themselves are stored in jQuery.cache, if jQuery isn't there, you don't need this code at all...since nothing was bound. However, it is a valid point that if jQuery is present, why not just use .unbind()?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.