views:

3521

answers:

2

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
Thanks, really helpful!
Corey Hart
I actually liked your first example better, the $.data(elem, 'events') supplies much more information.
Corey Hart
i added that as a comment
meder
Why don't you just use $('body').data('events')?
J-P
A: 

use jquery events filter http://www.codenothing.com/archives/jquery/event-filter/

you can use it like this

$("a:Event(click)")
fareed namrouti
Hah, thanks, built that plugin after getting meder's answer months ago.
Corey Hart
hahahah ok , np ;)
fareed namrouti
btw it's great plugin
fareed namrouti