1

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>
Rajan Chauhan
  • 1,378
  • 1
  • 13
  • 32
  • I see my code working here but can't figure out why it is not working on fiddle link i have given above http://jsfiddle.net/mAKOV/uoyzrLn6/4/ – Rajan Chauhan May 03 '15 at 23:49
  • In the jsfiddle you are declaring `clickdone` inside a `load` event listener. So it's not global. And thus can't be called using HTML event handlers content attributes. Please learn how to use tools like jsfiddle before asking questions here. SO is about code, not about jsfiddle. – Oriol May 03 '15 at 23:51
  • Because you have linked it to unavailable js file. See this [demo](http://jsbin.com/cehiworamo/1/) on jsbin it works too. – SaidbakR May 03 '15 at 23:51
  • Related: [Simple example doesn't work on JSFiddle](http://stackoverflow.com/questions/5431351/simple-example-doesnt-work-on-jsfiddle) – Jonathan Lonowski May 03 '15 at 23:51
  • I recommend to use [tag:jsbin] rather than [tag:jsfiddle]. – SaidbakR May 03 '15 at 23:52
  • But it is not even working on my local machine so i can't figure out the escape. Please suggest something else. – Rajan Chauhan May 03 '15 at 23:54
  • 1
    This one works: http://jsfiddle.net/8sh7mpmm/ – Paul May 03 '15 at 23:55
  • 1
    Another note: try to make the counter variable a global scope variable, i.e define it outside the function. for example, in your code, when I inspect the counter element, I could able to change the value and continue increasing the value that I have entered. – SaidbakR May 03 '15 at 23:57

1 Answers1

3

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/

jfriend00
  • 683,504
  • 96
  • 985
  • 979