vendredi 24 août 2018

If statement not working with color code

The code that I have says: whenever the 'a' key is pressed, the background changes. This doesn't happen, and I think it is because of the color code inside of the if statement.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>Tester</title>
    <script type="text/javascript">
    var colors = ['#ce0e0e', '#079b0c', '#3e3fd6']; //red, green, blue

    function changeBackground(){
      document.write("use 'a' key to change background");
      var colorAtRandom = colors[Math.floor(Math.random() * colors.length)];
      document.body.style.backgroundColor = colorAtRandom;
      document.getElementById('button').className = 'hidden'
    }

      window.addEventListener('keydown', checkKey, false);

    function checkKey(key){
      if (key.keyCode == 65){
        if (colorAtRandom != '#ce0e0e'){
          changeBackground();
        } else {
          alert('background is red');
        }
      }
    } 

</script>
<style>
  .hidden {
    display:none;
  }
  .show {
    display:block;
  }
</style>
</head>
<body>

<input id=button type=button value='change backgound color' onclick='changeBackground()'>

</body>
</html>

Aucun commentaire:

Enregistrer un commentaire