Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if element has click handler? [duplicate]

Tags:

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?

like image 416
kostepanych Avatar asked Dec 28 '12 15:12

kostepanych


People also ask

How do you know if an element has an Eventlistener?

To check if an element has event listener on it with JavaScript, we can call the getEventListeners function in the Chrome developer console. getEventListeners(document. querySelector("your-element-selector")); in the Chrome developer console to select the element we want to check with querySelector .

How do I check Eventlistener?

Right-click on the search icon button and choose “inspect” to open the Chrome developer tools. Once the dev tools are open, switch to the “Event Listeners” tab and you will see all the event listeners bound to the element. You can expand any event listener by clicking the right-pointing arrowhead.

What is click handler in JavaScript?

The onclick event generally occurs when the user clicks on an element. It allows the programmer to execute a JavaScript's function when an element gets clicked. This event can be used for validating a form, warning messages and many more. Using JavaScript, this event can be dynamically added to any element.


1 Answers

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.

like image 54
Snuffleupagus Avatar answered Oct 05 '22 13:10

Snuffleupagus