Reputation: 13
So I was following a tutorial where if you click a button the background color changes. I've completed the tutorial and I've understood most of the code, but I still can't figure out how the loop to get the hex number works
const hexNumber = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F']
const btn = document.getElementById('btn')
const color = document.querySelector('.color')
btn.addEventListener('click', function() {
let hexColor = "#";
// I can't understand how the loop down below works
for (let i = 0; i < 6; i++) {
hexColor += hexNumber[getRandomNumber()];
}
color.textContent = hexColor
document.body.style.background = hexColor
})
function getRandomNumber() {
return Math.floor(Math.random() * hexNumber.length)
}
Upvotes: 1
Views: 64
Reputation: 703
It's simpler than you think. Right now you have a variable hexColor="#"
As you know, a hex color is made of 6 bits, so you have a for loop from 0 to 5.
In your loop you have hexColor += hexNumber[getRandomNumber()];
but what is +=
? The instruction is equals to hexColor= hexColor + hexNumber[getRandomNumber()];
So you are appending 6 times a value. But which value? Well, it is defined by the function getRandomNumber()
which returns a value between 0 and hexColor
length. It's all here. A for loop which executes 6 times and append one of the array values, so you are going to have the hex color randomly generated.
Upvotes: 2