Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

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

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

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>

about 4 years ago · Juan Pablo Isaza Denunciar

0

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})`;
})
about 4 years ago · Juan Pablo Isaza Denunciar

0

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda