John
John

Reputation: 96

jQuery Code for click event

I attach a click handler to a button on my page. Is there anyway to find out what code is using jQuery?

$("#dreport").click(function() {
   var str = "hello";
});               

Is there a anyway to get the var str = "hello" in the firebug debugger, or anywhere?
I've tried alerting:

$("#dreport").attr("click")

But I only see [native code] where the body should be.

Upvotes: 1

Views: 1799

Answers (5)

krcko
krcko

Reputation: 2834

try with this code:

jQuery.fn.collectHandlers = function(event) {
   var ret = [],
       events = $(this).data('events');
   if (event in events) {
    for (var id in events[event]) {
       if (events[event][id] instanceof Function && events[event][id].toString) {
         ret.push(events[event][id].toString());
       }
     }
   }
  return ret;
}

they you can type this in firebug console: $('#btn').collectHandlers('click');. That will return array of functions attached as event listeners (via jQuery's bind family methods) for 'click' event.

Upvotes: 1

kaba
kaba

Reputation: 405

If what you want to show up in the log is: "hello" then do as Björn says. However if you want to output the logic in your function to the firebug console you can do like this:

$(document).ready(function(){
  var clickFunction = function(){
    var str = "hello";
    console.log(clickFunction);
  };
  $("#dreport").click(clickFunction);
});

This will show up in the firebug console as "function()" and if you click on it you will be taken to the function code in the source. You can also name the click function itself to e.g. "foo", to make it show up as "foo()" in firebug, like this:

var clickFunction = function foo(){
  var str = "hello";
  console.log(clickFunction);
};

Of course you can also use firebug's built in profiler in the console. Just click on profile, then click the element you want to profile, and then click profile again. This will output all function calls triggered when you clicked on your element.

Upvotes: 0

kͩeͣmͮpͥ ͩ
kͩeͣmͮpͥ ͩ

Reputation: 7846

$("#dreport").attr("click") is probably not what you think it is - jQuery uses the event model of the DOM (and even if it didn't, the attribute would be called "onclick" ;)

You could look at FireQuery that adds jQuery info to FireBug - including info about attached events.

And don't forget, you can type jQuery expressions into the FireBug console, and see the results, and $("#btn").click() will fire the click event.

Upvotes: 0

reko_t
reko_t

Reputation: 56430

You can also set breakpoints in firebug and inspect the variable contents in real-time.

Upvotes: 1

Björn
Björn

Reputation: 29381

console.log(str);

Or you can create your own JQuery-logger.

jQuery.fn.log = function (logMe) {
    console.log("%s says: %o", logMe, this);
    return this;
};

And then call it like;

$('#btn').log("logged!");

Upvotes: 2

Related Questions