196

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Corey Hart
  • 10,316
  • 9
  • 41
  • 47
  • 1
    so, in 1.8, all this is wrong? – Skylar Saveland Aug 17 '12 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](http://blog.jquery.com/2012/08/09/jquery-1-8-released/) – Anton Aug 19 '12 at 03:10

8 Answers8

145
$('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 omuraliev
  • 183,342
  • 71
  • 393
  • 434
  • 3
    I actually liked your first example better, the $.data(elem, 'events') supplies much more information. – Corey Hart Oct 03 '09 at 23:04
  • 17
    Why don't you just use $('body').data('events')? – James Oct 04 '09 at 13:50
  • 3
    gives me an error "$.data($('#myDiv').get(0), "events") is undefined" – zakdances Jan 07 '12 at 10:30
  • 8
    This only works for events bound through jQuery's helpers. – Alex Ciminian Feb 18 '12 at 18:00
  • 21
    $.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. – jbandi Aug 27 '13 at 21:21
  • 2
    I think [this](http://stackoverflow.com/questions/14072042/how-to-check-if-element-has-click-handler/14072162#14072162) is the simplest, non-clumsy and easy to understand way to check if a single element **has the event or not**. – Ganesh Jadhav Jan 08 '14 at 06:39
  • In this specific case of checking the body element, is it not better to directly write `document.body` in pure-javascript rather than going the jQuery route `$('body').get(0)` ? – WoodrowShigeru Jul 29 '15 at 11:03
  • important note: $._data when worked that at least an event bind to element. – Saeed Ahmadian May 10 '17 at 08:47
97

You may use:

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

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

amurra
  • 15,221
  • 4
  • 70
  • 87
Toni
  • 1,067
  • 7
  • 2
  • 1
    Does not help if you have used live to register the event. http://stackoverflow.com/questions/12755646/jquery-datatables-multiple-calls-to-event-handler-with-live-function – Rohit Banga Oct 06 '12 at 04:14
  • 33
    Question is to check if event exists on the element and not how to unbind existing events ... – Avi Oct 17 '12 at 18:01
  • 53
    @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?" – hans Apr 24 '13 at 19:28
  • this won't work if you don't want to destroy events registered elsewhere – Galvani Jun 30 '17 at 11:14
  • 8
    agree: not a strict answer to the OP but exactly what i needed ;) – tibi Sep 22 '17 at 14:52
  • 1
    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. – Bonez024 Sep 20 '22 at 18:53
57

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])
Tom G
  • 3,650
  • 1
  • 20
  • 19
28

use jquery event filter

you can use it like this

$("a:Event(click)")
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Fareed Alnamrouti
  • 30,771
  • 4
  • 85
  • 76
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. :)

rohtakdev
  • 956
  • 1
  • 13
  • 16
5

I wrote a plugin called hasEventListener which exactly does that.

Hope this helps.

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
Sebastien P.
  • 709
  • 7
  • 6
  • 1
    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: http://www.codingjack.com/playground/jquick/#haseventlistener, but I'm not using jquick, but I like that clean simplicity. – Nicholas Petersen Jul 28 '13 at 06:38
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
    });
-1

I ended up doing this

typeof ($('#mySelector').data('events').click) == "object"
Gargamel
  • 1,039
  • 1
  • 11
  • 15