Check if event exists on element [duplicate]
Asked Answered
C

8

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.

Cabalist answered 3/10, 2009 at 22:53 Comment(2)
so, in 1.8, all this is wrong?Moramorabito
@SkylarSaveland Method $.data(element, "events") was never official. But in jQuery 1.8.0 this method got left via $._data(element, "events"). read more hereImpresa
M
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.

Maxia answered 3/10, 2009 at 22:56 Comment(8)
I actually liked your first example better, the $.data(elem, 'events') supplies much more information.Cabalist
Why don't you just use $('body').data('events')?Valera
gives me an error "$.data($('#myDiv').get(0), "events") is undefined"Am
This only works for events bound through jQuery's helpers.Lithopone
$.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.Hyphenate
I think this is the simplest, non-clumsy and easy to understand way to check if a single element has the event or not.Chuff
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) ?Knockabout
important note: $._data when worked that at least an event bind to element.Timmytimocracy
S
99

You may use:

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

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

Sindee answered 4/5, 2011 at 14:40 Comment(6)
Does not help if you have used live to register the event. #12756146Irradiance
Question is to check if event exists on the element and not how to unbind existing events ...Repellent
@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?"Moue
this won't work if you don't want to destroy events registered elsewhereJennyjeno
agree: not a strict answer to the OP but exactly what i needed ;)Unpredictable
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.Escobedo
A
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])
Adventurism answered 15/10, 2012 at 15:46 Comment(3)
I think you can simplify this by using: var eventBound = (events != null);Bombastic
This solution works with jQuery 1.8.0 later. Thank you a lot Ton Gerken :)Nabonidus
This should be the accepted answer, it handles dynamically applied event handlers, even if the code is a handful. Thank you!Circumpolar
P
28

use jquery event filter

you can use it like this

$("a:Event(click)")
Phenice answered 22/8, 2010 at 12:45 Comment(3)
Hah, thanks, built that plugin after getting meder's answer months ago.Cabalist
As of 1.8, this plugin no longer worksCabalist
I love this, posting a plugin OP created as an answer to his question :)Ulane
I
5

I wrote a plugin called hasEventListener which exactly does that.

Hope this helps.

Interrex answered 1/3, 2011 at 13:25 Comment(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: codingjack.com/playground/jquick/#haseventlistener, but I'm not using jquick, but I like that clean simplicity.Carreno
P
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. :)

Poignant answered 13/7, 2012 at 0:12 Comment(1)
Not working any more in jQuery >= 1.8. See answer of Tom Gerken for a working solution.Hyphenate
A
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
    });
Antabuse answered 14/8, 2015 at 12:54 Comment(0)
M
-1

I ended up doing this

typeof ($('#mySelector').data('events').click) == "object"
Mylesmylitta answered 14/2, 2013 at 14:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.