My aim in the study is to generate random colors and apply them to the body background, but it doesn't work, why is it wrong?

enter image description here

what is the problem here function or addeventlistener?

`

const button = document.querySelector("button");

// Generate random color value and return it. EX 8a6cff
const getRandomColor = () => Math.floor(Math.random() * 0xffffff).toString(16);

const generateGradient = () => {
// Get random two colors for gradient
const color1 = getRandomColor();
const color2 = getRandomColor();

// Apply the gradient to the body background
document.body.style.background = 'linear-gradient(to left top, #${color1},   #${color2})';
}
generateGradient();

button.addEventListener("click", generateGradient);

`

>Solution :

there is mistake in block where you try to apply the gradient to the body background

You should replace (‘) quotes by backtick characters (`) in line where you use variables in string

<html>
<head>

</head>
<body>
<button id='color'>
COLOR
</button>
<script>
// Generate random color value and return it. EX 8a6cff
const getRandomColor = () => Math.floor(Math.random() * 0xffffff).toString(16);

const generateGradient = () => {
// Get random two colors for gradient
const color1 = getRandomColor();
const color2 = getRandomColor();

// Apply the gradient to the body background
document.body.style.background = `linear-gradient(to left top, #${color1},   #${color2})`;
}
generateGradient();

button = document.getElementById('color');
button.addEventListener("click", generateGradient);
</script>
</body>
</html>
document.body.style.background = `linear-gradient(to left top, #${color1},   #${color2})`;

Leave a Reply