Search code examples
javascripthtmlonclick

JavaScript - document.getElementByID with onClick


I'm trying to code a simple game in an HTML document just for fun. In it, there is an image which adds to your score when clicked.

I created a simple if statement within the score-adding function which should change the image and what its onClick value is...

if (foo == 1) {
    document.getElementById("test").src = "images/test2.png";
    document.getElementById("test").onClick = "foo2()";
}

...but it doesn't work. The image will be successfully changed, but the actual onClick remains the same. Checking the console, it throws no errors, either.


Solution

  • The onclick property is all lower-case, and accepts a function, not a string.

    document.getElementById("test").onclick = foo2;
    

    See also addEventListener.