I'm new to Stack Overflow so forgive me if I'm using this incorrectly. I am going through Colt Steele's excellent front-end web developers course and getting a feel for JavaScript. Here is some code that in Javascript that randomly generates a background color for a webpage when I click the button. The extra step that I tried adding myself was changing the color of the h1 to be white when the rgb values combined are less than 200. I print out the RGB values on the page itself and it appears the h1 element just randomly changes from black to white, not based on the value I presented in my if statement. Can anybody tell me why? Thank you.
`
const button = document.querySelector('button');
const h1 = document.querySelector('h1');
button.addEventListener('click', function() {
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
const newColor = randomColor();
document.body.style.backgroundColor = newColor;
// Set the color of the h1 element based on the luminosity
if (r g b < 200) {
h1.style.color = 'white';
} else {
h1.style.color = 'black';
}
h1.innerText = newColor;
})
const randomColor = () => {
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
return `rgb(${r}, ${g}, ${b})`;
}
`
CodePudding user response:
You are generating 2 sets of random values, one in the listener function which you use to determine h1 style, and the other in the randomColor function that you assign to the innerText. So the values you are printing out aren't the ones you're using for your <200 calculation.