Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
154
rated 0 times [  161] [ 7]  / answers: 1 / hits: 53937  / 12 Years ago, fri, december 28, 2012, 12:00:00

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?


More From » jquery

 Answers
97

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.


[#81184] Thursday, December 27, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
elijahm

Total Points: 674
Total Questions: 124
Total Answers: 79

Location: Northern Mariana Islands
Member since Fri, Jan 15, 2021
3 Years ago
elijahm questions
Thu, Dec 9, 21, 00:00, 3 Years ago
Mon, Aug 9, 21, 00:00, 3 Years ago
Fri, Mar 19, 21, 00:00, 3 Years ago
Wed, May 27, 20, 00:00, 4 Years ago
;