Reputation: 407
I want to find the code where an event listener was added to an element. Chrome's Element Inspector helps in showing which events were added, I'd like to find the code in which it was added and disable it.
Is there a way to jump to the location in source code where the atachement of event was made?
Upvotes: 0
Views: 151
Reputation: 1075587
Is there a way to jump to the location in source code?
You can (click the underlined jquery.min.js
to the right of the word document
). The problem is, it wouldn't help you much, because it would take you to jQuery's central event handler for that event for the element, not the specific handler you want to find. jQuery only hooks a given event on an element once; if there are multiple handlers attached with jQuery, it manages them itself (so it can ensure order and a few other things on older browsers).
It would be laborious, but you could override on
(which bind
and various other things end up calling anyway) and set a breakpoint in your overridden version (filtering for the event you're interested in, and optionally the element). Then run your page and look at the caller each time the breakpoint is hit.
Here's how you'd do a basic override of on
(immediately after loading jQuery):
var original = jQuery.fn.on;
jQuery.fn.on = function() {
/*...your logic here...*/
return original.apply(this, arguments);
};
...or alternately set a breakpoint within your jquery.js
file (don't try to use the minified version).
It may be slightly easier to override the internal jQuery.event.add
function instead, because all of the on
pre-processing has been done by that point:
var original = jQuery.fn.on;
jQuery.event.add = function(elem, types) {
if ((elem matches the one you care about) &&
/\bclick\b/i.test(types)) {
debugger;
}
return original.apply(this, arguments);
};
So for instance, if you only care about click
added to an element with id="foo"
, then:
var original = jQuery.fn.on;
jQuery.event.add = function(elem, types) {
if (elem.id === "foo" && // `elem` is a DOM element, not a jQuery object
/\bclick\b/i.test(types)) {
debugger;
}
return original.apply(this, arguments);
};
Upvotes: 2