I made a page to generate a random color with JavaScript and set that color to the background of the page.
//Global Variables
const hexChars = '0123456789ABCDEF';
const container = document.getElementById('container');
const hexText = document.getElementById('hex-text');
//Function to generate random hex code
function randomColor() {
let hexCode = '#';
for(i=0; i<=5; i++) {
let randomNum = Math.floor(Math.random() * 16);
hexCode += hexChars[randomNum];
}
return hexCode;
}
//Function to change page color & text
function applyColor() {
let hexCode = randomColor();
container.style.backgroundColor = hexCode;
hexText.innerHTML = hexCode;
}
//Make random color on page load, click, and spacebar press.
window.onload = applyColor();
container.onclick = () => applyColor();
document.body.onkeyup = e => {
if(e.keyCode == 32) {
applyColor();
}
}
* {
margin: 0;
padding: 0;
user-select: none;
}
#container {
position: absolute;
height: 100%;
width: 100%;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
transition: background-color .4s;
}
#hex-text {
font-family: sans-serif;
font-size: 2em;
color: white;
background-color: rgba(150, 150, 150, .6);
padding: .4em;
border-radius: 6px;
}
<div id="container">
<p id="hex-text">
#000000
</p>
</div>
How can I improve the efficiency or functionality of the JavaScript?
Edit: I'd also like to know if this is a fair generator, or if it's more likely to get one shade than another. I don't see why it would, but you never know.