598

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?

Ian
  • 50,146
  • 13
  • 101
  • 111
ages04
  • 6,337
  • 4
  • 19
  • 15
  • 5
    unfortunately, now: http://bugs.jquery.com/ticket/10589 – Skylar Saveland Aug 17 '12 at 18:52
  • 2
    support both jQuery pre and post 1.8: `var events = (jQuery._data || jQuery.data)(elem, 'events');` – oriadam Dec 31 '15 at 06:04
  • 3
    Note that you can use the FF and Chrome dev-tools (the F12) to see these event listeners. See https://developers.google.com/web/tools/chrome-devtools/debug/command-line/events#view-event-listeners-registered-on-dom-elements and https://developer.mozilla.org/en-US/docs/Tools/Page_Inspector/How_to/Examine_event_listeners – oriadam Apr 26 '16 at 20:43

16 Answers16

733

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" );
gnarf
  • 105,192
  • 25
  • 127
  • 161
jps
  • 11,347
  • 3
  • 23
  • 19
  • 246
    but you can still use `$._data($(elem).get(0), "events")` – bullgare Aug 18 '12 at 11:01
  • 10
    http://blog.jquery.com/2011/11/08/building-a-slimmer-jquery/ .data(“events”): jQuery stores its event-related data in a data object named (wait for it) events on each element. This is an internal data structure so in 1.8 this will be removed from the user data name space so it won’t conflict with items of the same name. jQuery’s event data can still be accessed via jQuery._data(element, "events") but be aware that this is an internal data structure that is undocumented and should not be modified. – Sam Greenhalgh Aug 20 '12 at 03:41
  • I've been using this method to try and find out the click event of a button. In the Chrome console it showed `handler: function () {` inside the click property. I had to double click on the function part for it to expand and show the full contents of the function. – Jim Feb 09 '15 at 10:34
  • @jim yeaaah, the double click is the answer – Adib Aroui May 18 '15 at 22:38
  • 2
    Seamlessly support both options: `var events = (jQuery._data || jQuery.data)(elem, 'events');` – oriadam Dec 31 '15 at 06:05
  • `function events(e) { $(e).each(function(){console.log(this);console.log($._data( this, "events" ));console.log("\n")}) }` A quick function yet useful –  Jun 02 '16 at 01:20
  • Worked great for me! Thanks! I used this to help write a testHandler function to test if a specific handler is attached to an objects event. https://stackoverflow.com/a/45448636/2512022 – ScottyG Aug 02 '17 at 19:21
  • can you get all the events of an element save them on a variable unbind the element and the rebind it? I need to disable a a href element and then rebind it after an event is complete – themhz Dec 07 '17 at 16:07
  • No! You should not be referencing method that start with an underscore. This is a hack. Those methods are private class methods, it's just that JS doesn't have proper classes so everything is exposed. This is just a bad development hack – Paul Allsopp Mar 21 '18 at 17:19
  • 1
    @CrazyMerlin ok, thanks for that. Now maybe you have a better answer? – enorl76 Apr 09 '18 at 18:44
  • 2
    it's returning undefined. – Rajat Sep 21 '20 at 16:08
94

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>
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • 2
    Works with 1.4, but not in jQuery 1.8.2. – Timo Kähkönen Dec 21 '12 at 21:15
  • 18
    For jQuery 1.8+, you **must** use the 'private data' method: `jQuery._data( jQuery("#el")[0], "events" );` instead of the 'public data' method: `jQuery("#el").data("events")`. The `events` object hasn't actually been stored in `.data()` for a long time, we trimmed a few bytes of code out by removing this "proxy" from the "public API" – gnarf Jan 10 '13 at 17:13
36

For jQuery 1.8+, this will no longer work because the internal data is placed in a different object.

The latest unofficial (but works in previous versions as well, at least in 1.7.2) way of doing it now is - $._data(element, "events")

The underscore ("_") is what makes the difference here. Internally, it is calling $.data(element, name, null, true), the last (fourth) parameter is an internal one ("pvt").

PhistucK
  • 2,466
  • 1
  • 26
  • 28
  • 1
    $._data("body", "events") undefined $().jquery; "1.7.1" (tried 1.7.2 and 1.8.1 all the time "undefined") – Mars Robertson Sep 12 '12 at 12:02
  • 2
    @Michal - http://api.jquery.com/jQuery.data/ says it accepts an element, not a selector. – PhistucK Sep 12 '12 at 15:08
  • 1
    Now works fine: $._data($("body").get(0), "events") Or even better: $("body").data("events") ! – Mars Robertson Sep 13 '12 at 11:12
  • 2
    FWIW - Pointing out that it 'internally' calls the other data function with a parameter we specifically don't document probably isn't needed. But yes, `jQuery._data( element, "events" )` is the 'correct' way to get this information now. – gnarf Jan 10 '13 at 17:11
35

Shameless plug, but you can use findHandlerJS

To use it you just have to include findHandlersJS (or just copy&paste the raw javascript code to chrome's console window) and specify the event type and a jquery selector for the elements you are interested in.

For your example you could quickly find the event handlers you mentioned by doing

findEventHandlers("click", "#el")
findEventHandlers("mouseover", "#el")

This is what gets returned:

  • element
    The actual element where the event handler was registered in
  • events
    Array with information about the jquery event handlers for the event type that we are interested in (e.g. click, change, etc)
    • handler
      Actual event handler method that you can see by right clicking it and selecting Show function definition
    • selector
      The selector provided for delegated events. It will be empty for direct events.
    • targets
      List with the elements that this event handler targets. For example, for a delegated event handler that is registered in the document object and targets all buttons in a page, this property will list all buttons in the page. You can hover them and see them highlighted in chrome.

You can try it here

Rui
  • 4,847
  • 3
  • 29
  • 35
13

I use eventbug plugin to firebug for this purpose.

Anton
  • 9,682
  • 11
  • 38
  • 68
  • Thanks, great tip. The extension adds a tab to Firebug ("Events") that shows the events of the page, so you can expore them easily. – Gruber Feb 26 '13 at 08:17
  • 12
    Also, Chrome Developer Tools has "Event Listeners" under the "Elements" tab and "Event Listener Breakpoints" under the "Sources" tab. – clayzermk1 Feb 27 '13 at 18:49
12

I've combined both solutions from @jps to one function:

jQuery.fn.getEvents = function() {
    if (typeof(jQuery._data) === 'function') {
        return jQuery._data(this.get(0), 'events') || {};
    }

    // jQuery version < 1.7.?
    if (typeof(this.data) === 'function') {
        return this.data('events') || {};
    }

    return {};
};

But beware, this function can only return events that were set using jQuery itself.

algorhythm
  • 8,530
  • 3
  • 35
  • 47
6

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])
Tom G
  • 3,650
  • 1
  • 20
  • 19
  • This `getEvents` method is overally great, but the thing is, it gives duplicate entries in IE11 (I know, IE again, but corporate needs it...). EDIT: $._data contains duplicate events for element, even though on FF it doesn't contain any... Weird IE world. But it's important to watch out for this possibility of having duplicate events. – Dominik Szymański Mar 26 '20 at 14:04
  • Oh, Tom, it's actually your code that's multiplying events with each execution of this method. Not good. – Dominik Szymański Mar 26 '20 at 14:28
5

As of 1.9 there is no documented way to retrieve the events, other than to use the Migrate plugin to restore the old behavior. You could use the _.data() method as jps mentions, but that is an internal method. So just do the right thing and use the Migrate plugin if you need this functionality.

From the jQuery documentation on .data("events")

Prior to 1.9, .data("events") could be used to retrieve jQuery's undocumented internal event data structure for an element if no other code had defined a data element with the name "events". This special case has been removed in 1.9. There is no public interface to retrieve this internal data structure, and it remains undocumented. However, the jQuery Migrate plugin restores this behavior for code that depends upon it.

oligofren
  • 20,744
  • 16
  • 93
  • 180
  • The accepted answer also clearly shows the new, **correct** way to get it for recent versions: `jQuery._data( elem, "events" );`... – Ian May 23 '13 at 21:21
  • 2
    A private, undocumented way will never be a *correct* way. The correct way - meaning documented, public, and intended - is to use the Migrate plugin. – oligofren May 27 '13 at 09:49
  • 4
    You seem to misunderstand the point of the Migrate plugin. jQuery removed deprecated features, and the Migrate plugin is to help **migrate** developer's code to the newer versions so that they can immediately take advantage of new features and improvements, but not lose functionality. It's meant to help the coder see what they need to do in order to start properly using new versions of jQuery. You shouldn't use it in production to **restore** features. Also, many things aren't documented and up to date in jQuery documentation - they've pointed it out before, so that's not a reason – Ian May 28 '13 at 15:17
  • Also, if it's included as a suggestion in the jQuery blog, I'd use it: http://blog.jquery.com/2012/08/09/jquery-1-8-released/ – Ian May 28 '13 at 15:17
  • Your reasoning on the Migrate plugin seems reasonable. OK if I delete my answer? – oligofren May 28 '13 at 15:41
4

I created a custom jQuery selector that checks against both jQuery's cache of assigned event handlers as well as elements that use the native method for adding them:

(function($){

    $.find.selectors[":"].event = function(el, pos, match) {

        var search = (function(str){
            if (str.substring(0,2) === "on") {str = str.substring(2);}
            return str;
        })(String(match[3]).trim().toLowerCase());

        if (search) {
            var events = $._data(el, "events");
            return ((events && events.hasOwnProperty(search)) || el["on"+search]);
        }

        return false;

    };

})(jQuery);

Example:

$(":event(click)")

This will return elements that have a click handler attached to them.

Erutan409
  • 730
  • 10
  • 21
3

In a modern browser with ECMAScript 5.1 / Array.prototype.map, you can also use

jQuery._data(DOCUMENTELEMENT,'events')["EVENT_NAME"].map(function(elem){return elem.handler;});

in your browser console, which will print the source of the handlers, comma delimited. Useful for glancing at what all is running on a particular event.

Jesan Fafon
  • 2,234
  • 1
  • 25
  • 29
  • `jQuery._data('ct100_ContentPlaceHolder1_lcsSection','events')["EVENT_NAME"].map(function(elem){return elem.handler;});` Uncaught TypeError: Cannot read property 'EVENT_NAME' of undefined at :1:62 – Mike W Mar 17 '17 at 20:30
  • `'ct100_ContentPlaceHolder1_lcsSection'` is a string, not a DOM Element. – Jesan Fafon Mar 17 '17 at 21:45
2

Events can be retrieved using:

jQuery(elem).data('events');

or jQuery 1.8+:

jQuery._data(elem, 'events');

Note: Events bounded using $('selector').live('event', handler) can be retrieved using:

jQuery(document).data('events')
R. Oosterholt
  • 7,720
  • 2
  • 53
  • 77
2

jQuery is not letting you just simply access the events for a given element. You can access them using undocumented internal method

$._data(element, "events")

But it still won't give you all the events, to be precise won't show you events assigned with

$([selector|element]).on()

These events are stored inside document, so you can fetch them by browsing through

$._data(document, "events")

but that is hard work, as there are events for whole webpage.

Tom G above created function that filters document for only events of given element and merges output of both methods, but it had a flaw of duplicating events in the output (and effectively on the element's jQuery internal event list messing with your application). I fixed that flaw and you can find the code below. Just paste it into your dev console or into your app code and execute it when needed to get nice list of all events for given element.

What is important to notice, element is actually HTMLElement, not jQuery object.

function getEvents(element) {
    var elemEvents = $._data(element, "events");
    var allDocEvnts = $._data(document, "events");
    function equalEvents(evt1, evt2)
    {
        return evt1.guid === evt2.guid;
    }

    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] = [];
                    }
                    if(!elemEvents[evntType].some(function(evt) { return equalEvents(evt, evts[i]); })) {
                        elemEvents[evntType].push(evts[i]);
                    }
                }
            }
        }
    }
    return elemEvents;
}
Dominik Szymański
  • 763
  • 10
  • 22
1

I have to say many of the answers are interesting, but recently I had a similar problem and the solution was extremely simple by going the DOM way. It is different because you don't iterate but aim directly at the event you need, but below I'll give a more general answer.

I had an image in a row:

<table>
  <td><tr><img class="folder" /></tr><tr>...</tr></td>
</table>

And that image had a click event handler attached to it:

imageNode.click(function () { ... });

My intention was to expand the clickable area to the whole row, so I first got all images and relative rows:

tableNode.find("img.folder").each(function () {
  var tr;

  tr = $(this).closest("tr");
  // <-- actual answer
});

Now in the actual anwer line I just did as follows, giving an answer to the original question:

tr.click(this.onclick);

So I fetched the event handler directly from the DOM element and put it into the jQuery click event handler. Works like a charm.

Now, to the general case. In the old pre-jQuery days you could get all events attached to an object with two simple yet powerful functions gifted to us mortals by Douglas Crockford:

function walkTheDOM(node, func)
{
  func(node);
  node = node.firstChild;
  while (node)
  {
    walkTheDOM(node, func);
    node = node.nextSibling;
  }
}

function purgeEventHandlers(node)
{
  walkTheDOM(node, function (n) {
    var f;

    for (f in n)
    {
      if (typeof n[f] === "function")
      {
        n[f] = null;
      }
    }
  });
}
pid
  • 11,472
  • 6
  • 34
  • 63
1

Try jquery debugger plugin if you're using chrome: https://chrome.google.com/webstore/detail/jquery-debugger/dbhhnnnpaeobfddmlalhnehgclcmjimi?hl=en

Marquinho Peli
  • 4,795
  • 4
  • 24
  • 22
0

Another way to do it is to just use jQuery to grab the element, then go through actual Javascript to get and set and play with the event handlers. For instance:

var oldEventHandler = $('#element')[0].onclick;
// Remove event handler
$('#element')[0].onclick = null;
// Switch it back
$('#element')[0].onclick = oldEventHandler;
tempranova
  • 929
  • 9
  • 13
0

I combined some of the answers above and created this crazy looking but functional script that lists hopefully most of the event listeners on the given element. Feel free to optimize it here.

var element = $("#some-element");

// sample event handlers
element.on("mouseover", function () {
  alert("foo");
});

$(".parent-element").on("mousedown", "span", function () {
  alert("bar");
});

$(document).on("click", "span", function () {
  alert("xyz");
});

var collection = element.parents()
  .add(element)
  .add($(document));
collection.each(function() {
  var currentEl = $(this) ? $(this) : $(document);
  var tagName = $(this)[0].tagName ? $(this)[0].tagName : "DOCUMENT";
  var events = $._data($(this)[0], "events");
  var isItself = $(this)[0] === element[0]
  if (!events) return;
  $.each(events, function(i, event) {
    if (!event) return;
    $.each(event, function(j, h) {
      var found = false;        
      if (h.selector && h.selector.length > 0) {
        currentEl.find(h.selector).each(function () {
          if ($(this)[0] === element[0]) {
            found = true;
          }
        });
      } else if (!h.selector && isItself) {
        found = true;
      }

      if (found) {
        console.log("################ " + tagName);
        console.log("event: " + i);
        console.log("selector: '" + h.selector + "'");
        console.log(h.handler);
      }
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="parent-element">
  <span id="some-element"></span>
</div>
Marek Lisý
  • 3,302
  • 2
  • 20
  • 28