In this tutorial, I will be showing how I built a hex color generator. It is a simple page that generates a random hexadecimal color code when you click a button and updates the background of the page to correspond with the generated color code.
The markup
I decided to make the page very simple, giving it only a heading containing a span tag that will display the value of the current background color, and a button.
<body>
<div class="container">
<h1>Hex Color: <span class="hexValue">#ffffff</span></h1>
<button id="btn">Click to generate new color</button>
</div>
</body>
Styles
I gave the page a default background color of white, added a transition effect to make the color change smoother and set its height and width to that of the viewport which is the user's visible area of a web page. Then I went ahead to center the contents of the page using CSS Flexbox:
body {
background: #ffffff;
font-family: 'Lato', sans-serif;
transition: background 0.3s;
}
.container {
height: 100vh;
width: 100vw;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
letter-spacing: 0.1em;
}
Functionality
First thing I did was to create references to the necessary HTML elements and the button in the JS file.
const button = document.querySelector('#btn');
const body = document.querySelector('body');
const value = document.querySelector('.hexValue');
Then I stored all hexadecimal values in an array and added a click
event listener to the button:
const hexValues = [0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F'];
button.addEventListener('click', changeHex);
I defined the callback function of the event listener as follows:
function changeHex() {
let hex = '#';
for(let i = 0; i < 6; i++){
const index = Math.floor(Math.random() * hexValues.length)
hex += hexValues[index];
}
value.textContent = hex;
body.style.backgroundColor = hex;
}
Every time the button is clicked, the changeHex
function is called which creates a variable hex
and sets its value to #. Then it loops over the hexValues
array 6 times and each time generates a random number using Math.random()
.
Now, the Math.random()
function picks a random number between 0 and 1 (not including 1) and returns a decimal but we don't want decimals. So what do we do if we want a whole number larger than 1? We multiply it by the number we want (in this case, the length of the hexValues
array) and wrap it within the Math.floor()
function which returns the largest integer less than or equal to a given number. It basically rounds it down to the nearest whole number. This makes sure that any number generated is a valid hexValues
index.
The random whole number generated is appended to a new variable index
. I can now access the hexValues
array item in the position corresponding to the generated index
number using bracket notation, then add it to the end of the hex
variable i.e hex += hexValues[index]
. Then the cycle repeats itself until the 6th round is over at which time a full 6-digit hex code will have been generated.
Updating the page
All that's left is to set the textContent
of the span
tag and the background color of the page to be the value of hex
. And that's all!
Conclusion
We've successfully built a random hex color generator using HTML, CSS and a few lines of JavaScript. I hope you learnt a lot from my method. You can find the complete code on my GitHub repository. There are certainly other ways to achieve the same result so do check them out and give them a try.
Thanks a lot for reading, and happy coding!
Top comments (9)
Awesome job on the project!
Did you know you can input hex directly using
0x...
notation, and write it to a string usingNumber#toString(16)
? So you can simplify your random number generation something like this:😁
The first one won't produce any colors with red in them —
2 ** 16
is0x10000
, whereas the size of the full RGB color space is0x1000000
(2 ** 24
) 😉Yup, typo. Cheers
Another:
Really nice. I did something similar on a project I worked on except the users aren't really aware of what's going on. With your permission I'd like to turn this into a video tutorial and give due credit.
Sure, that'll be great. Go ahead!
Thank you!
very nice