javascriptif-statementbackground-colorcolor-codes

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.

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');
      }
   }
}
.hidden {
    display:none;
}
.show {
    display:block;
}
<input id=button type=button value='change backgound color' onclick='changeBackground()'>


Note by the editor: The original code had the script wrapped in a <script> tag inside <head> with no load event listener. I couldn't reproduce that for the snippet. To see the original code please refer to the revisions.


Solution

  • The problems lies within the scoping. the variable colorAtRandom cant be found within the function checkKey(). make this global and it will work.

    The second problem whas that the event listener was not working. i changed it so it will be added wenn the button is clikced. Because document.write creates a new document you will lose the eventlistener you created at loading. therefore it is not advised.

    this should fix it.

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8"/>
        <title>Tester</title>
        <script type="text/javascript">
        var colors = ['#ce0e0e', '#079b0c', '#3e3fd6']; //red, green, blue
    	
    	var colorAtRandom = colors[Math.floor(Math.random() * colors.length)]; // this variable has to be global.
    	
        function changeBackground(){
          //document.write("use 'a' key to change background");  using document.write is not advised. 
          colorAtRandom = colors[Math.floor(Math.random() * colors.length)]; // chose new random color. made it global to get rid of scope
          document.body.style.backgroundColor = colorAtRandom;
          document.getElementById('button').className = 'hidden';
    	  window.addEventListener('keydown', checkKey, false); // add the event listener when button is pressed. 
        }
        function checkKey(key){
    	console.log("test");
          if (key.keyCode == 65){
            if (colorAtRandom != '#ce0e0e'){
              changeBackground();
            } else {
              alert('background is red');
    		  changeBackground();		// change background after alert so it doesnt get stuck.
            }
          }
        } 
    </script>
    <style>
      .hidden {
        display:none;
      }
      .show {
        display:block;
      }
    </style>
    </head>
    <body>
    <input id=button type=button value='change backgound color' onclick='changeBackground()'>
    </body>
    </html>