Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

145
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!