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

157
Vistas
Background color won't change based on an array string

so i'm trying to do a project i found in https://jsbeginners.com/hex-change-background-color-project/ where i have a button and when its clicked, it changes the color of the background accompanied with a hex code for the color. i've seen some solutions for it but i'm wondering why mine isn't working

Javascript:

const colors = ['#C78283;', '#B80C09;', '#6B2B06;', '#E5E7E6;', '#B7B5B3;', '#CBE896;', '#FFFFFC;', '#FF7F11;', '#FF1B1C;',
 '#493657;', '#CE7DA5;', '#BEE5BF;', '#DFF3E3;', '#FFD1BA;', '#EF233C;', '#FCAF58;', '#FF8C42;', '#F4B860;'];

 
btn.addEventListener('click', ()=> {
    span.innerText= colors[Math.floor(Math.random() *colors.length)];
    document.body.style.background.color = colors.values;
});

everything works including the span changing to a random hex code from the array except the background color, it doesn't change. can someone help?

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

0

Issues.

  • There should not be any ; in the color list.
  • Setting background color with colors.values is incorrect. colors is an array. So you have to access it using the correct index
  • The background should be set with document.body.style.backgroundColor

I have redefined the code by keeping the random color in a string and setting the same value to span content and background color.

const btn = document.getElementById('btn');
const span = document.getElementById('hex');
const colors = ['#C78283', '#B80C09', '#6B2B06', '#E5E7E6', '#B7B5B3', '#CBE896', '#FFFFFC', '#FF7F11', '#FF1B1C',
  '#493657', '#CE7DA5', '#BEE5BF', '#DFF3E3', '#FFD1BA', '#EF233C', '#FCAF58', '#FF8C42', '#F4B860'];

btn.addEventListener('click', () => {
  const color = colors[Math.floor(Math.random() * colors.length)];
  span.innerText = color;
  document.body.style.backgroundColor = color;
});
<button id="btn">Click Me</button>
<span id="hex"></span>

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