test if event handler is bound to an element in jQuery [duplicate]

test if event handler is bound to an element in jQuery [duplicate]

This question already has an answer here:

jQuery find events handlers registered with an object

14 answers

Is it possible to determine whether an element has a click handler, or a change handler, or any kind of event handler bound to it using jQuery?
Furthermore, is it possible to determine how many click handlers (or whatever kind of event handlers) it has for a given type of event, and what functions are in the event handlers?

Solutions/Answers:

Solution 1:

You can get this information from the data cache.

For example, log them to the console (firebug, ie8):

console.dir( $('#someElementId').data('events') );

or iterate them:

jQuery.each($('#someElementId').data('events'), function(i, event){

    jQuery.each(event, function(i, handler){

        console.log( handler.toString() );

    });

});

Another way is you can use the following bookmarklet but obviously this does not help at runtime.

Solution 2:

Killing off the binding when it does not exist yet is not the best solution but seems effective enough! The second time you ‘click’ you can know with certainty that it will not create a duplicate binding.

Related:  AngularJS - How to use ng-if without HTML element

I therefore use die() or unbind() like this:

$("#someid").die("click").live("click",function(){...

or

$("#someid").unbind("click").bind("click",function(){...

or in recent jQuery versions:

$("#someid").off("click").on("click",function(){...

Solution 3:

I wrote a plugin called hasEventListener which exactly does that :

http://github.com/sebastien-p/jquery.hasEventListener

Hope this helps.

Solution 4:

This solution is no more supported since jQuery 1.8 as we can read on the blog here:

$(element).data(“events”): This is now removed in 1.8, but you can still get to the
events data for debugging purposes via $._data(element, “events”).
Note that this is not a supported public interface; the actual data
structures may change incompatibly from version to version.

So, you should unbind/rebind it or simply, use a boolean to determine if your event as been attached or not (which is in my opinion the best solution).

Solution 5:

I think this might have updated with jQuery 1.9.*

I’m finding the this is the only thing that works for me at the moment:

$._data($("#yourElementID")[0]).events

Solution 6:

I wrote a very tiny plugin called “once” which do that:

$.fn.once = function(a, b) {
    return this.each(function() {
        $(this).off(a).on(a,b);
    });
};

And simply:

$(element).once('click', function(){
});