Matt Matt - 7 months ago 11
HTML Question

Showing image if variable is 10

A few days ago I started learning JavaScript and now I'm trying to make a code which could show a photo after 10 clicks on button (which is also a image).

Here's my code. It counts but doesn't want to show me a photo.jpg

HTML:

<img src="button.png" onClick="add();" /> <br />
<input type="text" id="number" value="0"></input>
<span id="win"></span>


JavaScript:

var count = 0;
function add() {
document.getElementById('number').value = ++count;
}

if ("count" === 10) {
document.getElementById('win').innerHTML = "<img src='photo.jpg' id='win' />";
}

Answer

One of the issues that you have is that you are comparing a string "count" against your expected number 10, which will never evaluate as true.

Just remove the quotes around your count variable in your if-statement :

if (count === 10) {
    document.getElementById('win').innerHTML = "<img src='photo.jpg' id='win' />";
}

So each time you call your add() function, increment your count and perform your check :

// Your counter
var count = 0;
// Your add function (triggered by your button)
function add() {
      document.getElementById('number').value = ++count;
      // Determine if you should show your image after your count was incremented
      if (count === 10) {
           document.getElementById('win').innerHTML = "<img src='photo.jpg' id='win' />";
      }
}
Comments