javascriptdebuggingfirebug

Debug which Javascript runs with an element is clicked on


Consider an element <img id='hitMe' /> which is referenced in a jQuery function with either $('#hitme').click() or possibly $(document).on('click', '#hitme'). How can I find these functions in the Javascript source code, other than grepping for the string hitme? Consider that grepping is not feasible as the string may have an arbitrarily large amount of references, and there may be a very large number of imported Javascript files.

Perhaps there might be a way to have Firebug step into Javascript functions that are run, after page load, on a line-by-line basis? Consider that I don't know where to set a breakpoint because I don't know which function is run.


Solution

  • Here's a solution that catches the moment in which the event is trigger (dispatched) rather than the moment in which the listener is being added (on/click).

    It can be done by overriding jQuery.event.dispatch. for example:

    (function($){
        var old = $.event.dispatch;
        $.event.dispatch = function(event){
            if(event.type=='click'){
                var handlers = ( $._data( this, "events" ) || {} )[ event.type ] || [];
                console.log('handlers', handlers[0]);
            }
            old.apply(this, arguments);
        };
    })(jQuery);
    

    In this example I chose to print the content of the function to the console, but it could also be useful to debug it like Omri Sivan suggested, with debugger;. With Chrome you should be able to right click on the function to "Show function definition".