How to Build a Hex Color Generator in JavaScript
If you want to create your own color generator using JavaScript, then you’re welcome to our tutorial. In this snippet, we are going to build a hex color generator step by step.
If you want to create your color generator using JavaScript, then you’re welcome to our tutorial.
We know, that colors are defined either in an <kbd class="highlighted">RGB</kbd> or <kbd class="highlighted">Hex</kbd> format, for example, #000000 (black) or #C0C0C0(grey). For generating the number, we use the Math.random JavaScript function, which returns random numbers between 0 and 1. Here is how this function looks like:
JavaScript hex color generator
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 <kbd class="highlighted">.toString(16)</kbd> at the end of the <kbd class="highlighted">Math.random</kbd> function. Here is how it will look like:
JavaScript hex color generator
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 <kbd class="highlighted">.slice(2,8)</kbd> at the end of the <kbd class="highlighted">Math.random</kbd> 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:
JavaScript hex color generator
Finally, the hex value must be set as a background. This can be done using another function, which will set <kbd class="highlighted">getColor()</kbd> to a variable and will define the <kbd class="highlighted">document.body.style.background </kbd> equal to that variable.
Here’s how it looks like:
JavaScript hex color generator
After all these steps, you can press the <kbd class="highlighted"> Run </kbd>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 <kbd class="highlighted"> setBackground() </kbd> 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 <kbd class="highlighted"> setBackground() </kbd> function in case the code for <kbd class="highlighted"> spacebar (keyCode of 32)</kbd> pressed.
So the <kbd class="highlighted"> document.body.keyup</kbd> must be equal to the function, and the function must include an if statement which states that if the <kbd class="highlighted">.keyCode==32</kbd> , <kbd class="highlighted"> setBackground() </kbd> should run.
Here’s an example of the code. <kbd class="highlighted">Press space</kbd> on the keyboard to see the result:
JavaScript hex color generator