Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I debug why handler for "click" JavaScript event doesn't get called?

I've installed a handler for the click JavaScript event of a <button> element using the jQuery API, but the handler doesn't get called when the button is in fact clicked. How can I debug why the event handler isn't invoked? I'm developing in Visual Studio 2010 and debugging with the help of Google Chrome Developer Tools.

I'm new to JavaScript and don't know the debugging methods :)

EDIT

This is the HTML declaration of the button in question:

<button id="start-lint">Submit</button>

The relevant JavaScript:

$('button').button();
var btn = $("button#start-lint");
log.debug("Button: %s", btn);
btn.click(function () {
    log.debug("Button clicked");
});

Let me know if more information is needed.

EDIT 2

Somehow I got it working, not sure what was wrong in the first place, but at least now I know how to tell if an element was found or not!

like image 207
aknuds1 Avatar asked Dec 28 '22 15:12

aknuds1


2 Answers

You can only debug if the code is actually fired, which it seems to not be.

You could try to see if its even finding the selector using length. alert($("#myselector").length); or console.log($("#myselector").length);

For debugging javascript i recommend you to use FIREBUG for Firefox (http://getfirebug.com/) - you can set breakpoints, write to console etc, and it gives all possible displays of variables, objects etc. Tutorial can be found here: http://www.youtube.com/watch?v=2xxfvuZFHsM

(You said you where new to jQuery/Javascript, so hope it helped :D)

like image 90
Marco Johannesen Avatar answered Dec 31 '22 15:12

Marco Johannesen


Inline JavaScript is executed as the page loads, so if the button is defined after the JavaScript the code won't find it and so can't attach the handler. You need to put that JavaScript in the document ready (or onload) function, which means it will be executed after the button (and everything else on the page) has loaded, and/or put it after the button in the source.

like image 29
nnnnnn Avatar answered Dec 31 '22 15:12

nnnnnn