Rajan Chauhan
Rajan Chauhan

Reputation: 1375

Javascript code for a increment counter based on number of clicks not working?

I was working on Udacity Javascript design course I need to increase the counter when image is clicked each time. But eventually I can't figure out what is wrong here that is not letting the code work. The link in Jfiddle is http://jsfiddle.net/mAKOV/uoyzrLn6/4/

function clickdone() {
  var catpic = document.getElementById("catpic");
  var counter = document.getElementById("counter");
  var count = counter.innerHTML;
  count++;
  counter.innerHTML = count;
}
<img id="catpic"
     src="http://apurrfectcat.files.wordpress.com/2011/08/2-cats.jpg" 
     style="height:400px; width:600px;"
     onclick="clickdone();" />
<br>
<div>
  <p>Cat Count</p>
  <span style="text:bold;">:</span>
  <span id="counter">0</span>
</div>

Upvotes: 1

Views: 421

Answers (1)

jfriend00
jfriend00

Reputation: 707328

Your jsFiddle does not work because you have to set the onload setting in the upper left to No Wrap in <head>. This allows your clickdone() function definition to be in the global scope where the click handler can find it. As you had it, your function was defined inside an onload handler function which means it is in a private scope and the click handler cannot access it.

And, you also had a typo, missing the "f" in "function".

Changing that makes it work fine here: http://jsfiddle.net/jfriend00/uoyzrLn6/3/

Upvotes: 3

Related Questions