Is there a way to check if an event exists in jQuery? I'm working on a plugin that uses namespaced events on made up events, and would like to be able to check if the event is binded to an element or not.
+11
A:
$('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.
meder
2009-10-03 22:56:26
Thanks, really helpful!
Corey Hart
2009-10-03 23:02:23
I actually liked your first example better, the $.data(elem, 'events') supplies much more information.
Corey Hart
2009-10-03 23:04:06
i added that as a comment
meder
2009-10-03 23:08:25
Why don't you just use $('body').data('events')?
J-P
2009-10-04 13:50:25
A:
use jquery events filter http://www.codenothing.com/archives/jquery/event-filter/
you can use it like this
$("a:Event(click)")
fareed namrouti
2010-08-22 12:45:33
Hah, thanks, built that plugin after getting meder's answer months ago.
Corey Hart
2010-08-22 16:03:17