Whenever I click a button on the browser it displays a random color along with its rgb(r,g,b) code. I made 3 variables r, g, and b which produce random numbers from 0 to 255 using the basic logic of Math.floor(Math.random()*256);
My problem is that sometimes the random colors generated are too dark and the rgb code displayed along with them is black in color.
I tried writing a logic that whenever r+g+b < 300, toggle the h1 element's class which has a property of color white.
const h1 = document.querySelector('h1');
const button = document.querySelector("button");
h1.classList.add('h1');
//if (r+g+b < 500)
button.addEventListener('click', () => {
changeColor();
});
const changeColor = (() => {
const newColor = randomColor();
document.body.style.backgroundColor = newColor;
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})`;
})
A simple way is to make the r, g, b variables have a wider scope so they can be used to do your <500 test in the same place that you change the background color.
const h1 = document.querySelector('h1');
const button = document.querySelector("button");
let r, g, b;
h1.classList.add('h1');
button.addEventListener('click', () => {
changeColor();
});
const changeColor = (() => {
const newColor = randomColor();
document.body.style.backgroundColor = newColor;
if (r + g + b < 500) h1.style.color = 'white';
else h1.style.color = 'black';
h1.innerText = newColor;
});
const randomColor = (() => {
r = Math.floor(Math.random() * 256);
g = Math.floor(Math.random() * 256);
b = Math.floor(Math.random() * 256);
return `rgb(${r}, ${g}, ${b})`;
})
<h1></h1>
<button>click me</button>
Well, you have to put your if inside this function (randomColor ) and when the values are generated for (r,g,b) you're if for the new values will be checked again every time the values change.
const randomColor = (() => {
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
if(r+g+b < 300){
h1.classList.add('h1');
}
return `rgb(${r}, ${g}, ${b})`;
})
Try This:
const changeColor = (() => {
const newColor = randomColor();
document.body.style.backgroundColor = newColor[1];
h1.innerText = newColor[1];
const sumColor = newColor[0];
if (sumColor < 300){
h1.style.color = white;
}else{
h1.style.color = black;
}
}
);
const randomColor = (() => {
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
const sum = r+g+b;
return [sum,`rgb(${r}, ${g}, ${b})`]; //returning array
})