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?
Issues.
; in the color list.colors.values is incorrect. colors is an array. So you have to access it using the correct indexdocument.body.style.backgroundColorI 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>