29

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.

BinaryButterfly
  • 18,137
  • 13
  • 50
  • 91
Poyo
  • 554
  • 1
  • 9
  • 23

5 Answers5

54

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

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

See also addEventListener.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
17

In JavaScript functions are objects.

document.getElementById('foo').onclick = function(){
    prompt('Hello world');
}
Marco
  • 155
  • 1
  • 4
Who iscoo
  • 303
  • 2
  • 12
6

Perhaps you might want to use "addEventListener"

document.getElementById("test").addEventListener('click',function ()
{
    foo2();
   }  ); 

Hope it's still useful for you

Manuel Castillo
  • 371
  • 4
  • 4
3
window.onload = prepareButton;

function prepareButton()
{ 
   document.getElementById('foo').onclick = function()
   {
       alert('you clicked me');
   }
}

<input id="foo" value="Click Me!" type="button" />
DinoMyte
  • 8,737
  • 1
  • 19
  • 26
iftkhar
  • 31
  • 2
-1

Sometimes JavaScript is not activated. Try something like:

<!DOCTYPE html>
<html>
  <head>

    <script type="text/javascript"> <!--
      function jActivator() {
        document.getElementById("demo").onclick = function() {myFunction()};
        document.getElementById("demo1").addEventListener("click", myFunction);
        }
      function myFunction( s ) {
        document.getElementById("myresult").innerHTML = s;
        }
    // --> </script>
    <noscript>JavaScript deactivated.</noscript>
    <style type="text/css">
    </style>
  </head>
  <body onload="jActivator()">
    <ul>
      <li id="demo">Click me -&gt; onclick.</li>
      <li id="demo1">Click me -&gt; click event.</li>
      <li onclick="myFunction('YOU CLICKED ME!')">Click me calling function.</li>
    </ul>
    <div id="myresult">&nbsp;</div>
  </body>
</html>

If you use the code inside a page, where no access to is possible, remove and tags and try to use 'onload=()' in a picture inside the image tag '