I made a random color generator and while it generates the random colors and displays the numbers, when it gets very dark on the page I wanted the h1 to become white and the button to become black if it became very bright.
const button = document.getElementById('button');
const h1 = document.getElementById('h1');
button.addEventListener('click', function (){
const r = Math.floor(Math.random() * 255);
const g = Math.floor(Math.random() * 255);
const b = Math.floor(Math.random() * 255);
const newColor = `rgb(${r}, ${g}, ${b})`;
document.body.style.backgroundColor = newColor;
h1.innerText = newColor;
});
button.addEventListener('click', function (){
if(parseFloat(r >= 150 || g >= 150 || b >= 150)) {
document.button.style.backgroundColor = '#000';
document.button.style.color = '#fff';
} else if(parseFloat(r >= 60 || g >= 60 || b >= 60)) {
document.h1.style.color = '#fff';
}
});
I think there is an issue with my parseFloat but I am unsure. I think the issue is that the number becomes a string and isn't converted back properly?
Right now my code just does not respond to the second portion where I ask the 'if' statements.
You need to do everything in one function, because the variables aren't visible in the second function.
There's also no need to call parseFloat()
. You already have numbers in those variables.
document.button
and document.h1
should just be button
and h1
.
button.addEventListener('click', function() {
const r = Math.floor(Math.random() * 255);
const g = Math.floor(Math.random() * 255);
const b = Math.floor(Math.random() * 255);
const newColor = `rgb(${r}, ${g}, ${b})`;
document.body.style.backgroundColor = newColor;
h1.innerText = newColor;
if (r >= 150 || g >= 150 || b >= 150) {
button.style.backgroundColor = '#000';
button.style.color = '#fff';
} else if (r >= 60 || g >= 60 || b >= 60) {
h1.style.color = '#fff';
}
});