Search code examples
javascriptfunctionif-statementincrement

How do I make an event occur on 5 clicks of an image in JavaScript?


I have tried to make it work but it just doesn't. I'm trying to change the background image on 5 clicks, but even putting a simple alert in the else statement of my function doesn't trigger it.

<img  src="images\Wheel1.png" id="Wheel1" onclick="changeImage();lights();" />

<script>

function lights() { 

     var count = 0;
    
      if (count < 5) {
        count++;
      } else {
        document.body.background = "images/BackgroundLight.jpg";
      }
    
}

Solution

  • you have to declare the variable outside the function :

    var count = 0;
    
    function lights() {
      if (count < 5) {
        count++;
      } else {
        document.body.background = "images/BackgroundLight.jpg"
      }
    }