1

I'm working on a project and I designed a custom ripple, but I need to name of the css variable I wanted apply the ripple on, something like this

function setRipple(){
       // I want my ripple to be like this
          var elementColor = // The button background-color variable name;
          var ripple color = `var(--${elementColor}-tint)`


       // Other things goes here
     }
:root{
  --color-primary: #00cc67;
  --color-primary-shade: #008040;
  --color-primary-tint: #e5fff2;
}


.btn{
      background-color:var(--color-primary)
  }
<html>
<body>
 <button class="btn">Ripple button</button>
</body>
</html>
Emmanuel
  • 19
  • 2

1 Answers1

1

This is fragile, but it sets the ripple value by appending -tint to the element color as you specified.

The function looks into the first (and only the first) stylesheet in the document, finds the :root rule, and inspects the list of CSS "--color-" variable keys found there. When it finds one whose value matches the button's color, it uses that key to make the rippleColor string.

The fragility comes mostly from the way color matching is done (and there must be a better way to do this.) Also, if there were, for some reason, several variable keys with the same matching value, the last match would be selected.

Thanks for the puzzle. Stylesheet manipulation is a fascinating beast.

let rippleColor = setRipple();
console.log(`ripple color will be: ${rippleColor}`)

function setRipple() {

  let elementColorName = "";
  const
    btn = document.querySelector(".btn"),
    btnColorVal = getComputedStyle(btn)
      .getPropertyValue("background-color")
      .toString(),
    firstSheet = document.styleSheets[0],
    rules = Array.from(firstSheet.cssRules);
    
  rules
    .filter(r => r.type === 1 && r.selectorText === ":root")
    .map(rule => {
      Object.entries(rule.style)
        .filter(entry => parseInt(entry[0]) > -1)
        .forEach(entry => {
          const
            varName = entry[1],
            varVal = getComputedStyle(document.documentElement)
              .getPropertyValue(varName).trim(),
            match = hexToRgb(varVal) === btnColorVal;
          if(match){ elementColorName = varName; }
        });
    });
    console.log("the button's color is: " + elementColorName);
    const rippleColor = `var(${elementColorName}-tint)`;
    return rippleColor;
}

function hexToRgb(hex){
  const c = '0x' + hex.slice(1);
  return 'rgb(' + [
    (c >> 16) & 255, (c >> 8) & 255, c & 255
  ].join(', ') + ')';
}
:root {
  --color-primary: #00cc67;
  --color-primary-shade: #008040;
  --color-primary-tint: #e5fff2;
}

.btn {
  background-color: var(--color-primary)
}
<html>
<body>
  <button class="btn">Ripple button</button>
</body>
</html>
Cat
  • 4,141
  • 2
  • 10
  • 18