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

Get random gradient background color

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:

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 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.

>Solution :

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>
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