199

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 bound to an element or not.

2
  • 1
    so, in 1.8, all this is wrong? Commented Aug 17, 2012 at 18:19
  • 4
    @SkylarSaveland Method $.data(element, "events") was never official. But in jQuery 1.8.0 this method got left via $._data(element, "events"). read more here Commented Aug 19, 2012 at 3:10

8 Answers 8

146
$('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.

Sign up to request clarification or add additional context in comments.

8 Comments

I actually liked your first example better, the $.data(elem, 'events') supplies much more information.
Why don't you just use $('body').data('events')?
gives me an error "$.data($('#myDiv').get(0), "events") is undefined"
This only works for events bound through jQuery's helpers.
$.data() is not working any more in jQuery >= 1.8. For me $._data() is working in jQuery 1.10.1. See answer of Tom Gerken for a working solution.
|
100

You may use:

$("#foo").unbind('click');

to make sure all click events are unbinded, then attach your event

6 Comments

Does not help if you have used live to register the event. stackoverflow.com/questions/12755646/…
Question is to check if event exists on the element and not how to unbind existing events ...
@Avi, it's still a good answer, because in many cases the question is asked with the problem in mind: "How not to register a handler twice?"
agree: not a strict answer to the OP but exactly what i needed ;)
As of jQuery 3.0, .unbind() has been deprecated. It was superseded by the .off() method since jQuery 1.7, so its use was already discouraged.
|
58

To check for events on an element:

var events = $._data(element, "events")

Note that this will only work with direct event handlers, if you are using $(document).on("event-name", "jq-selector", function() { //logic }), you will want to see the getEvents function at the bottom of this answer

For example:

 var events = $._data(document.getElementById("myElemId"), "events")

or

 var events = $._data($("#myElemId")[0], "events")

Full Example:

<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
        <script>
            $(function() {
                $("#textDiv").click(function() {
                    //Event Handling
                });
                var events = $._data(document.getElementById('textDiv'), "events");
                var hasEvents = (events != null);
            });
        </script>
    </head>
    <body>
        <div id="textDiv">Text</div>
    </body>
</html>

A more complete way to check, that includes dynamic listeners, installed with $(document).on

function getEvents(element) {
    var elemEvents = $._data(element, "events");
    var allDocEvnts = $._data(document, "events");
    for(var evntType in allDocEvnts) {
        if(allDocEvnts.hasOwnProperty(evntType)) {
            var evts = allDocEvnts[evntType];
            for(var i = 0; i < evts.length; i++) {
                if($(element).is(evts[i].selector)) {
                    if(elemEvents == null) {
                        elemEvents = {};
                    }
                    if(!elemEvents.hasOwnProperty(evntType)) {
                        elemEvents[evntType] = [];
                    }
                    elemEvents[evntType].push(evts[i]);
                }
            }
        }
    }
    return elemEvents;
}

Example usage:

getEvents($('#myElemId')[0])

3 Comments

I think you can simplify this by using: var eventBound = (events != null);
This solution works with jQuery 1.8.0 later. Thank you a lot Ton Gerken :)
This should be the accepted answer, it handles dynamically applied event handlers, even if the code is a handful. Thank you!
28

use jquery event filter

you can use it like this

$("a:Event(click)")

3 Comments

Hah, thanks, built that plugin after getting meder's answer months ago.
As of 1.8, this plugin no longer works
I love this, posting a plugin OP created as an answer to his question :)
5

Below code will provide you with all the click events on given selector:

jQuery(selector).data('events').click

You can iterate over it using each or for ex. check the length for validation like:

jQuery(selector).data('events').click.length

Thought it would help someone. :)

1 Comment

Not working any more in jQuery >= 1.8. See answer of Tom Gerken for a working solution.
5

I wrote a plugin called hasEventListener which exactly does that.

Hope this helps.

1 Comment

The problem is, how does it work? I've been at it for some hours, and its still not clear. I just want to check if there is a click event on it, and get a boolean back, not an object, but most those methods you provide, at least the examples, are far more complicated. Interestingly: codingjack.com/playground/jquick/#haseventlistener, but I'm not using jquick, but I like that clean simplicity.
0

This work for me it is showing the objects and type of event which has occurred.

    var foo = $._data( $('body').get(0), 'events' );
    $.each( foo, function(i,o) {
    console.log(i); // guide of the event
    console.log(o); // the function definition of the event handler
    });

Comments

-1

I ended up doing this

typeof ($('#mySelector').data('events').click) == "object"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.