Search code examples
javascriptrandomcolorsrgb

How to avoid generating too black colors at random in JavaScript?


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})`;
})


Solution

  • 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>