smythluke smythluke - 1 year ago 85
Javascript Question

JavaScript Error: Uncaught TypeError: foo is not a function

For some reason JavaScript doesn't seem to recognise my function.

I have a button in some HTML:

<button type="button" class="btn btn-default" id="lightOn" onclick="lightOn()">On</button>

and then a bit of JavaScript:

function lightOn(){
socket.emit("setting", {"light":"on"});

When I click on the button I get the error:

Uncaught TypeError: lightOn is not a function

Any idea why this won't work?


Answer Source

The problem is you give to your element the same id : "lightOn". In this scope lightOn is the element, which shadows the function.

A simple solution would be to give a different name to the element or to the function.

A better one would be to separate the script from the HTML:

<button type="button" class="btn btn-default" id="lightOn">On</button>

    $('#lightOn').click(function() {
        socket.emit("setting", {"light":"on"});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download