Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

`

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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})`;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading