jQuery – Find event handlers for a DOM element

As a JavaScript developer, you will eventually find yourself debugging code someone else wrote.  Unit tests only cover so much and most tests are written in an isolated environment.  The truth in JS is when an application is running.

When using third-party libraries and code you haven’t written (legacy code), it is useful to be able to figure out what’s going on before implementing a new feature or fixing buggy code. A poorly-written (or poorly-understood) library can sneak in event handlers that can wreak havoc on code that seemed straightforward.

In a real-world application, elements can have several event handlers that can react to user interaction. An event handler can perform operations on data models, update UI elements, send API requests, and more.

In jQuery, you can easily attach an event handler to a user-initiated action with the $.on method:

$('#target_element').on('click', function(e) {
    // do something when the user clicks on the #target_element

It would be convenient to be able to list event handlers that are registered for a DOM element.

Luckily, the jQuery library gives us access to such a feature!

$._data(rawDomElementTarget), 'events');

In the above code example, we pass a raw DOM Element to the $_data() function.  Make sure you do not pass a jQuery object ($(‘some_element’)), use vanilla JS to get the element or the .get() method to get access.

Check out this jsFiddle for an example on how to use this feature.

If you click the top-right button in the previous example, you’ll notice that waypoints.js has registerd a ‘resize’ event handler. If your application registers another ‘resize’ handler on that element, you could potentially run into problems, problems that can be incredibly difficult to debug.

jQuery has some great debugging tools outside of its fantastic API.  Use the $._data() method to help debug your next project!

Happy coding!