I want to know what JavaScript function is allocated to the events of an HTML element, an input, for example. I would like to check if it has any function bound to the onmouseover, or onclick, or any other event.
2 Answers
In plain JavaScript, that information is not accessible.
So, your options:
- Some frameworks like you track event listeners provided you used their syntax to bind them (like jQuery).
- Some libraries will "rewrite" how event tracking works (like VisualEvent)
- Lastly, you can write your own wrapper around the add/removeEventListener functions, so that it tracks that information in addition to calling the native add/removeEventListener functions. Making sure it wraps all the possible ones, though, can be a challenge.
9 Comments
Marco Florian
Used VisualEvent but didn't show anything on the element I'm debugging.
Marco Florian
I did an alert of the .onclick prop and it showed me the function bound to the element.
alert(document.getElementById("...").onclick);. You can add that as a sample to your last recommendation. This was not added using jQuery. I think that is the reason why VisualEvent does not show anything. Thanks, didn't think about it first.Mike 'Pomax' Kamermans
onclick and any on... in plain JS is old-style (effectively deprecated) hard coded event handling, and very easy to check by simply running through the list of known names: if(obj.onclick) { ... }. However, in modern JS you don't have that option because we use addEventListener("click",fn) and removeEventListener("click", fn) for registering and dropping handlers.Marco Florian
Make sense, this is JavaScript wrote by another programmer and didn't know how it was implemented. Using addEventListener sounds good. But how to know what Event was bound to an element? alert(.onclick); isn't the right way? This addEventListener line might be on a really large JavaScript file and so hard to find.
Mike 'Pomax' Kamermans
it would be, so the very first question is "why do you need to know". If you have a good enough reason, you may want to either switch to a framework that does it for you, or write a shim that gets loaded as first script, and changes how addEventListener/removeEventListener works.
|
Inspect your input box in Google Chrome browser, you can check the Event Listeners tab. You can also make use of timeline to track the firing events and effectively use DOM break points.
1 Comment
Marco Florian
This is interesting. I checked Chrome and its event listener tab, but didn't really know how to use it. I added all the three breakpoints in there (sub-tree modifications, attr modifications, node removal) and when I click on the button, page is reloaded without breaking on any point. I guess because there is no breakpoint on page reload. Also, in the Event Listener tab, there is no info about the name of the function or where is it located.