21

Possible Duplicate:
test if event handler is bound to an element in jQuery

Tried to do the following (link is jQuery object of 'a' tag):

 link.data("events") //undefined even if link has event handlers
 jQuery.data(link, 'events') //undefined always also
 jQuery._data(link, 'events') //undefined always also

using jquery-1.8.3

So, how to check if element has click handler?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
kostepanych
  • 2,229
  • 9
  • 32
  • 47

1 Answers1

37

You can use jQuery._data to check for events. The first argument should be a reference to the HTML element, not the jQuery object.

var ev = $._data(element, 'events');
if(ev && ev.click) alert('click bound');

Sample below.

$(function(){
    $('#test').click(function(){
        // NOTE: this below is refering to the HTML element, NOT the jQuery element
        var ev = $._data(this, 'events');
        if(ev && ev.click) alert('click bound to this button');
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<button id="test">Click me to check for click handlers</button>

Also note that this method for checking events will only work when the event is bound via jQuery. If the event is bound via element.attachEventListener, element.onclick, <a onclick="doStuff()"> or any other non jQuery way, this will not work. If you're fitting into this boat, check this answer.

Community
  • 1
  • 1
Snuffleupagus
  • 6,365
  • 3
  • 26
  • 36
  • @Blossoming_Flower Can you elaborate? This is working for me on jQuery versions 2.1.3 and 1.11.0. – Snuffleupagus May 12 '15 at 20:17
  • My apologies, it was an error on my part. I've deleted my comment. – timetofly May 12 '15 at 20:39
  • @Ionian316 `undefined == false` so `if(ev && ev.click)` does the same thing. – Snuffleupagus Jul 15 '15 at 19:22
  • @Snuffleupagus Yes, I was in the process of editing my comment, but got timed out. What I wanted to say was that if you want to check to see if an event handler has been bound before binding one, you can use `if (typeof ev === "undefined" || !ev.click) element.click(clickEventHandler);`. – Ionian316 Jul 15 '15 at 19:27