lundi 25 janvier 2016

Javascript - Random, if statement, and event.target

I'm new to Javascript and I have an issue with event.target. The thing is that I use Math.random to display a number, then use an if statement so that if you click on the image corresponding to the number, it gets bigger, and if you click on another image, its opacity changes. It works perfectly in Chrome and IE, but not in Firefox (which is a classic, I know).

Here's my code:

<html>
<body>
  <input class="img" type="image" id="soleil" src="img/soleil.jpg" alt="soleil">

  <input class="img" type="image" id="jour" src="img/jour.jpg" alt="jour">

  <input class="img" type="image" id="nuit" src="img/nuit.jpg" alt="nuit">

 <script>

var sunrise_sunset = [19, 20 ,6, 7];
   var night = [21, 22, 23, 0, 1, 2, 3, 4, 5];
   var day = [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18];
   var hours = sunrise_sunset.concat(night).concat(day);

   var randomHour = Math.floor(Math.random() * hours.length);

{document.getElementById("soleil").addEventListener("click", function(){checkAnswer(sunrise_sunset)}, false);
                          document.getElementById("nuit").addEventListener("click", function(){checkAnswer(night)}, false);
                          document.getElementById("jour").addEventListener("click", function(){checkAnswer(day)}, false);
}

function checkAnswer(array) {  
  var isCorrect = false;
  for(var i = 0; i<array.length; i++) {
    if(array[i] == randomHour){
        isCorrect = true;
      break;
    }
  }

  if(isCorrect){

        event.target.style.width=500;

  }else{

      event.target.style.opacity = 0.5;
  }
};
</script>
</body>
</html>

So my question is, how can I make it work in Firefox? Should I just change my if statement? I read tons of posts in which they redefine the event through a function, but I don't see how I can do that with the random value and the if statement. I'm not saying there is no way, just that I don't see it...

Anyway, thank you in advance for your help guys! :)




Aucun commentaire:

Enregistrer un commentaire