views:

44

answers:

3

Is there a way to find all of the events for a element in javascript? or a way to unbind all events from a element?

Thanks.

A: 

Of course ! Take a look at this to bind/unbind events http://api.jquery.com/category/events/ and use this jQuery code fragment to get all the events bound to an element in the form of a hashset of keypairs "eventname/function delegate"

jQuery(elem).data('events');
NinjaCross
This only works if you're already using jQuery.
Matt Ball
is there a way to do it without jQuery?
errorhandler
Well, afaik everything's needed is to include the jQuery API. That code chunk should work also for events not directly bound by jQuery.
NinjaCross
A: 

If you don't want ot use jQuery, a quick and dirty way (and there's bound to be a better one) would be to loop through the element's parameters and check for functions that begin with 'on' (onclick etc).

var el = document.getElementById('elementid') ;
el.onclick = function(e) { console.log('Clicked!') ; } ; // Attached test event.
if(typeof(el)=='object') {
   for(var i in el) {
      if(i.substr(0,2) == 'on' && typeof(el[i])=='function') {
         el[i] = function() {} ; // Unbind with null function.
      }
   }
}
Gus
thanks, I'll give it a try
errorhandler
doesn't work for me :(
errorhandler
+1  A: 

There is not way to do that directly using javascript.

Jquery has a couple of functions to keep track of that data.

One "pure" way to do that is to change the addEventListener/attachEvent function through prototyping (search about javascript prototype stuff, not the framework).

Or if you have a custom function to hadle adding/removing events you can tune it.

Well, that's it.

Dave
I am using a custom function to addEvents (handle ie etc). is there a way to save all of the events (names and functions) added to a element?
errorhandler
Hi errorhandler, I suspect that you were using a custom function to handle IE addEvent. Well, I think you can tune this function, adding to a global var/object with the event data - target element, target event, and callback function, and then in this custom var/object, add some functions to retrieve the needed data.
Dave