smythluke smythluke - 7 months ago 10
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(){
$("#lightOn").addClass("active");
$("#lightOff").removeClass("active");
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?

Thanks.

Answer

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>

$(function(){
    $('#lightOn').click(function() {
        $("#lightOn").addClass("active");
        $("#lightOff").removeClass("active");
        socket.emit("setting", {"light":"on"});
    });
});
Comments