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
CodePudding user response:
Use below code . It worked
document.getElementById('container').style.background = `linear-gradient(to right, ${hex1} , ${hex2} )`;
CodePudding user response:
First, here is a tip: never use 'var', use 'let' instead.
There is no setProperty()
function in JS, you need to use element.style["style you want to change"] = "what you want to change it to"
.
And, you should not wrap the variables in '{}'s, or they become not variables, so the code should be:
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["background-image"] = "linear-gradient(to right, " hex1 ", " hex2 ")";
document.getElementById("description").innerHTML = "The code of the color is: linear-gradient( 270deg, " hex1 ", " hex2 " );";
};
Also, if you are using a div, you have to define height too.