Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery find events handlers registered with an object

Tags:

jquery

dom

events

I need to find which event handlers are registered over an object.

For example:

$("#el").click(function() {...}); $("#el").mouseover(function() {...}); 

$("#el") has click and mouseover registered.

Is there a function to find out that, and possibly iterate over the event handlers?

If it is not possible on a jQuery object through proper methods, is it possible on a plain DOM object?

like image 939
ages04 Avatar asked Mar 25 '10 18:03

ages04


2 Answers

As of jQuery 1.8, the event data is no longer available from the "public API" for data. Read this jQuery blog post. You should now use this instead:

jQuery._data( elem, "events" ); 

elem should be an HTML Element, not a jQuery object, or selector.

Please note, that this is an internal, 'private' structure, and shouldn't be modified. Use this for debugging purposes only.

In older versions of jQuery, you might have to use the old method which is:

jQuery( elem ).data( "events" ); 
like image 101
jps Avatar answered Sep 19 '22 18:09

jps


You can do it by crawling the events (as of jQuery 1.8+), like this:

$.each($._data($("#id")[0], "events"), function(i, event) {   // i is the event type, like "click"   $.each(event, function(j, h) {     // h.handler is the function being called   }); }); 

Here's an example you can play with:

$(function() {    $("#el").click(function(){ alert("click"); });    $("#el").mouseover(function(){ alert("mouseover"); });      $.each($._data($("#el")[0], "events"), function(i, event) {      output(i);      $.each(event, function(j, h) {          output("- " + h.handler);      });    });  });    function output(text) {      $("#output").html(function(i, h) {          return h + text + "<br />";      });  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>  <div id="el">Test</div>  <code>      <span id="output"></span>  </code>
like image 33
Nick Craver Avatar answered Sep 21 '22 18:09

Nick Craver