JavaScript
x
21
21
1
function myFunction2() {
2
for (let i=1; i < 3; i++){
3
if (i<2){
4
var numhex = (Math.random() * 0xfffff * 1000000).toString(16);
5
var hex1 = '#' + numhex.slice(0, 6);
6
// return hex1;
7
// console.log(hex1);
8
}
9
else {
10
var numhex = (Math.random() * 0xfffff * 1000000).toString(16);
11
var hex2 = '#' + numhex.slice(0, 6);
12
// return hex2;
13
// console.log(hex2);
14
}
15
16
}
17
// document.getElementById("container").style.backgroundImage = "linear-gradient(to right, " + {hex1} + ", " + {hex2} + ")";
18
document.getElementById("container").setProperty("background-image", "linear-gradient(to right, " + {hex1} + ", " + {hex2});
19
document.getElementById("description").innerHTML = "The code of the color is: linear-gradient( 270deg, " + hex1 + ", " + hex2 + " );";
20
};
21
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
JavaScript
1
2
1
document.getElementById('container').style.background = `linear-gradient(to right, ${hex1} , ${hex2} )`;
2