I am trying to get a random gradient from colorArr. I have this code:
const colorArr = [
"#e5e2ff",
"#ffd3e1",
"#c7f7dc",
"#fdfdbd",
"#ff8787",
];
const getRandomColor = () => {
return colorArr[Math.floor(Math.random() * colorArr.length)];
};
and it perfectly picks random plain color.
When I use something like this:
const colorArr = [
"linear-gradient(-225deg, #7de2fc 0%, #b9b6e5 100%)",
"linear-gradient(-225deg, #7de2fc 0%, #b9b6e5 100%)",
"linear-gradient(-225deg, #7de2fc 0%, #b9b6e5 100%)",
"linear-gradient(-225deg, #7de2fc 0%, #b9b6e5 100%)",
"linear-gradient(-225deg, #7de2fc 0%, #b9b6e5 100%)",
];
It gives me white backgrounds instead of the actual gradients.
CodePudding user response:
You need to use background-image
to use linear-gradient
instead of backgroundColor
try the following code.
const colorArr = [
"linear-gradient(-225deg, #7de2fc 0%, #b9b6e5 100%)",
"linear-gradient(-225deg, #7de2fc 0%, #b9b6e5 100%)",
"linear-gradient(-225deg, #7de2fc 0%, #b9b6e5 100%)",
"linear-gradient(-225deg, #7de2fc 0%, #b9b6e5 100%)",
"linear-gradient(-225deg, #7de2fc 0%, #b9b6e5 100%)",
];
const getRandomColor = () => {
return colorArr[Math.floor(Math.random() * colorArr.length)];
};
const div = document.querySelector("div");
div.style.backgroundImage = getRandomColor();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div style="width: 100px; height: 100px"></div>
</body>
</html>