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?
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:
And that image had a click event handler attached to it:
My intention was to expand the clickable area to the whole row, so I first got all images and relative rows:
Now in the actual anwer line I just did as follows, giving an answer to the original question:
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:
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
This is what gets returned:
The actual element where the event handler was registered in
Array with information about the jquery event handlers for the event type that we are interested in (e.g. click, change, etc)
Actual event handler method that you can see by right clicking it and selecting Show function definition
The selector provided for delegated events. It will be empty for direct events.
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
I've combined both solutions from @jps to one function:
But beware, this function can only return events that were set using jQuery itself.
Try jquery debugger plugin if you're using chrome: https://chrome.google.com/webstore/detail/jquery-debugger/dbhhnnnpaeobfddmlalhnehgclcmjimi?hl=en
In a modern browser with ECMAScript 5.1 /
Array.prototype.map
, you can also usein 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.
You can do it like this:
If you're on jQuery 1.4+, this will alert the event and functions bound to it:
You can play with it on jsFiddle here