Search code examples
stringgradientstr-replacealphargba

Convert RGB to RGBA at 0.9 alpha in string


I need to take the color gradient and dynamically change rgb to rgba and add 0.9 alpha, or some other number. Of course div id="gradient" can have more than three rgb and rgba colors. I tried replace ((')', ', 0.9)'). Replace ('rgb', 'rgba'); but it does not work. How do I do this?

The result should look like:

linear-gradient(90deg, rgba(205, 55, 55, 0.7) 11%, rgba(80, 55, 205, 0.9) 45%, rgba(55, 205, 73, 0.5) 79%)

function myFunction() {
  var gradient = document.getElementById("gradient").style.background;
  document.getElementById("demo").innerHTML = gradient.replace(')', ', 0.9)').replace('rgb', 'rgba');
}
<div id="gradient" style="background: linear-gradient(
90deg
, rgba(215, 45, 45, 0.7) 11%, rgb(73, 45, 215) 45%, rgba(45, 215, 65, 0.5) 79%);"></div>

<button onclick="myFunction()">Click me</button>

<p id="demo"></p>


Solution

  • To replace directly in the style, you could use the code below. However, if possible, you should instead have the different styles in a css file then just switch the whole element style (ex. gradient-idle to gradient-clicked or whatever your needs are) on click.

    function myFunction() {
        var gradient = document.getElementById("gradient")
            .style
            .background
            .replace(/rgb\([0-9]{1,3},\s[0-9]{1,3},\s[0-9]{1,3}/, "$&, 0.75") // put another alpha here instead of 0.75
            .replace("rgb(", "rgba("); // then replace rgb( with rgba(
    
        document.getElementById("demo").innerHTML = gradient;
        document.getElementById("demo").style.background = gradient;
    }
    <div id="gradient" style="
        background: linear-gradient(90deg,
        rgba(205, 55, 55, 0.7) 11%,
        rgb(80, 55, 205) 45%,
        rgba(55, 205, 73, 0.5) 79%);"></div>
    
    <button onclick="myFunction()">Click me</button>
    <p id="demo"></p>