Search code examples
javascriptjqueryhtmlcsslinear-gradients

Dynamically update Linear Gradient CSS


How to dynamically change the argument value of linear-gradient using javascript / Jquery? I have to change both color and its percentage as per user choice and the range slider value respectively. I have written the below code, but it is not working. As we have to put linear-gradient in " " and due to double quotation mark all arguments turn into simple string.

var gradColor1 = `${this.color1} ${percentage}%`;
var gradColor1 = `${this.color1} ${percentage}%`;
slider.style.background =linear-gradient(to left, gradColor1, gradColor1);

Solution

  • The issue is because you need to concatenate the values in to a string which you set as the value of style.backgroud. As you're already using template literals, try this:

    slider.style.background = `linear-gradient(to left, ${gradColor1}, ${gradColor1})`
    

    Note that if you want to specify a gradient you'll need two colours, like this:

    var percentage1 = 50;
    var color1 = "#C00";
    var percentage2 = 100;
    var color2 = "#000";
    
    slider.style.background = `linear-gradient(to left, ${color1} ${percentage1}%, ${color2} ${percentage2}%)`;
    #slider {
      width: 200px;
      height: 200px;
    }
    <div id="slider"></div>

    Finally, note that unless you're calculating colours dynamically in JS, it would be a much better idea to set the background using CSS only, like this:

    #slider {
      width: 200px;
      height: 200px;
      background: linear-gradient(to left, #C00 50%, #000 100%);
    }
    <div id="slider"></div>