I am trying to assign the following css to an element but it isn’t assigning the css to the element. Is this the best way to do this? Not sure what I am doing wrong.
var col1 = "#616161";
var col2 = "#ffffff";
var cssStr = '"background": "linear-gradient(180deg, '+col+', '+col2+')", "background-clip": "text", "-webkit-text-fill-color": "transparent"';
console.log("CssStr: " + cssStr);
$(this).css({cssStr})
In Console Log:
CssStr: "background": "linear-gradient(180deg, #616161, #ffffff)", "background-clip": "text", "-webkit-text-fill-color": "transparent"
2
Answers
You can’t create an object by putting the string representation of the properties inside
{}
. Just create the object directly, and substitute the variables into one of the property values. The easiest way to substitute variables is using a template literal instead of concatenation.You are trying to convert a string to an object and pass an object to
.css()
. You cannot do the former and you should pass key-value pairs to the latter. I have commented out your second rule, because in this fiddle it prevented any graphics from manifesting: