Check if event exists on element

Corey Hart picture Corey Hart · Oct 4, 2009 · Viewed 255.1k times · Source

Is there a way to check if an event exists in jQuery? I’m working on a plugin that uses custom namespaced events, and would like to be able to check if the event is binded to an element or not.

Answer

meder omuraliev picture meder omuraliev · Oct 4, 2009
$('body').click(function(){ alert('test' )})

var foo = $.data( $('body').get(0), 'events' ).click
// you can query $.data( object, 'events' ) and get an object back, then see what events are attached to it.

$.each( foo, function(i,o) {
    alert(i) // guid of the event
    alert(o) // the function definition of the event handler
});

You can inspect by feeding the object reference ( not the jQuery object though ) to $.data, and for the second argument feed 'events' and that will return an object populated with all the events such as 'click'. You can loop through that object and see what the event handler does.