skip to Main Content

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


  1. 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.

    var css = {
        "background": `linear-gradient(180deg, ${col}, ${col2})`, 
        "background-clip": "text", 
        "-webkit-text-fill-color": "transparent"
    };
    
    $(this).css(css);
    
    Login or Signup to reply.
  2. 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:

    var col1 = "#616161";
    var col2 = "#ffffff";
    var cssStr = {
        "background": "linear-gradient(180deg, "+col1+", "+col2+")", 
        /*"background-clip": "text",*/
        "-webkit-text-fill-color": "transparent"
    };
    let context = $("#abc");
    Object.keys(cssStr).map(item => context.css(item, cssStr[item]));
    #abc {
        width: 200px;
        height: 200px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="abc"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search