Now we need to convert the number to a string with a hexadecimal value. To do that, we use the toString() method. We are going to add .toString(16) at the end of the Math.random function. Here is how it will look like:
The first step is done, but that’s not all. We need to remove the (0) and (.) and limit the result to 6 characters. In this case, we will use the slice() method by adding the .slice(2,8) at the end of the Math.random function. Why 2 and 8? As we want to get six characters, we should slice the result, starting with the first two characters and ending at the eighth character. Here’s the code:
Finally, the hex value must be set as a background. This can be done using another function, which will set getColor() to a variable and will define the document.body.style.background equal to that variable.Here’s how it looks like:
After all these steps, you can press the Run button and see a random color every time. To prevent refreshing all the time, we should generate a new color every time the button is clicked. All we need to do is adding the setBackground() function at the end and tell the browser when to run it.
You probably guess that the best way of doing that is using an if statement that will run the setBackground() function in case the code for spacebar (keyCode of 32) pressed.
So the document.body.keyup must be equal to the function, and the function must include an if statement which states that if the .keyCode==32 , setBackground() should run.
Here’s an example of the code. Press space on the keyboard to see the result: