Search code examples
javascriptjquerycsslinear-gradientsradial-gradients

jQuery Syntax: -linear-gradient("color", white) with "color" as variable


I have a <div> that changes its color depending on a percentage given just like this

ProgressBar.color = function(value, maxVal) {
    var bcolor;
    var color;
    var percentage = (value / maxVal) * 100;
    //For each percentage, different colors
    if (percentage >= 0 && percentage < 25) {
        bcolor = "green";
        color = "black";
    } else if (percentage >= 25 && percentage < 50) {
        bcolor = "yellow";
        color = "green";
    } else if (percentage >= 50 && percentage < 75) {
        bcolor = "orange";
        color = "blue";
    } else if (percentage >= 75 && percentage <= 100) {
        bcolor = "red";
        color = "black";
    }

    //Setters
    $('#bar').css("background-color", bcolor);
    $('#bar').css("color", color);
};

but now I want to add some gradient effects. My question is:

  • What is the syntax for -linear-gradient() when you are using a variable as a color?

I have this, but its not working:

$('#bar').css("background", "-moz-linear-gradient('bcolor', white, 'bcolor')");

Solution

  • You just need to concat the variable as follow:

    $('#bar')
        .css("background", "-moz-linear-gradient(" + bcolor + ", white, " + bcolor + ")");
    //                                           ^^^^^^^^^^^^^^^        ^^^^^^^^^^^^^^