Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

146
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda