skip to Main Content

I am trying to make a background gradient be set randomly by a onload function but it does not execute somewhere in the code.

<html>
  <script>
    const g = [
  "color: blue; linear-gradient(to top, #e0eafc, #cfdef3);",
  "color:purple; linear-gradient(to top, #eecda3, #ef629f);",
  "color: green; linear-gradient(to top, #00d2ff, #928dab);"
];

    
    function rg() { document.body.style.background = g[Math.floor(Math.random()*g.length)];
    }

  </script>

<body onload="rg()">
    <h1>Game Library</h1>
    <div class="game">
      <a href="/games/1"><img src="/icons/game1.png" alt="Game 1"></a>
      <p>Madalin stunt cars 2</p>
    </div>
  </body>

<style>
    body {
  font-family: custom;
  margin: 0;
  padding: 0;
  height: 100%;
  background-repeat: no-repeat;
  background-attachment: fixed;

}
</style>
</html>

I got a white background, I was expecting a gradient.

2

Answers


  1. You have to have a valid value for the css, and the gradient needs to come first:

    const g = [
      "linear-gradient(to top, #e0eafc, #cfdef3), blue",
      "linear-gradient(to top, #eecda3, #ef629f), purple",
      "linear-gradient(to top, #00d2ff, #928dab), green"
    ];
    
        
    function rg() { 
        const i = Math.floor(Math.random()*g.length)
        document.querySelector('body').style.background = g[i];
    }
    <body onload="rg()">
        <h1>Game Library</h1>
        <div class="game">
          <a href="/games/1"><img src="/icons/game1.png" alt="Game 1"></a>
          <p>Madalin stunt cars 2</p>
        </div>
      </body>
    
    <style>
        body {
      font-family: custom;
      margin: 0;
      padding: 0;
      height: 100%;
      background-repeat: no-repeat;
      background-attachment: fixed;
    
    }
    </style>
    Login or Signup to reply.
  2. The css gradients in the array are not in the correct syntax.
    Replace the array with the correct css syntax for the gradient:

        const g = [
          "linear-gradient(to top, #e0eafc, #cfdef3)",
          "linear-gradient(to top, #eecda3, #ef629f)",
          "linear-gradient(to top, #00d2ff, #928dab)"
        ];
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search