Skip to content
Advertisement

how to set backgroundImage with javascript

function myFunction2() {
  for (let i=1; i < 3; i++){
    if (i<2){
      var numhex = (Math.random() * 0xfffff * 1000000).toString(16);
      var hex1 = '#' + numhex.slice(0, 6);
      // return hex1;
      // console.log(hex1);
    }
    else {
      var numhex = (Math.random() * 0xfffff * 1000000).toString(16);
      var hex2 = '#' + numhex.slice(0, 6);
      // return hex2;
      // console.log(hex2);
    }
    
  }
  // document.getElementById("container").style.backgroundImage = "linear-gradient(to right, " + {hex1} + ", " + {hex2} + ")";
  document.getElementById("container").setProperty("background-image", "linear-gradient(to right, " + {hex1} + ", " + {hex2});
  document.getElementById("description").innerHTML = "The code of the color is: linear-gradient( 270deg, " + hex1 + ", " + hex2 + " );";
};

Hello, I am trying to set two colors for linear-gradient as parameters inside a specific element’s background-image property, but it seems that something is wrong with my setProperty. Everything is working fine except this line of code. I’ve also tried it with style.backgroundImage with no result. I am new to js. Thanks in advance

Advertisement

Answer

Use below code . It worked

document.getElementById('container').style.background = `linear-gradient(to right, ${hex1} , ${hex2} )`;
Advertisement