Search code examples
javascriptinputcss-variablessetpropertyactionlistener

Is it possible to change a css variable using js setProperty with a value of another js variable?


I have an input field, in which, user is supposed to enter the color of text, that he want's to be displayed later. I was wondering, if there is a way to change css variables with javascript setProperty function, and instead of a value, the argument would be another javascript variable? for example:

elem.style.setProperty('--my-css-variable', anotherJsVariable);

Solution

  • Yes, just like you have.

    Doing this is most of the point of CSS custom properties.

    setTimeout(function() {
      const elem = document.getElementById("one");
      const anotherJsVariable = "yellow";
      elem.style.setProperty('--my-custom-property', anotherJsVariable);
    }, 750);
    #one {
      --my-custom-property: red;
      background-color: var(--my-custom-property);
    }
    
    #two {
      background-color: white;
    }
    
    #three {
      background-color: var(--my-custom-property);
    }
    
    div {
      display: inline-block;
      padding: 1em;
    }
    <div id="one">
      <div id="two">
        <div id="three">
    
        </div>
      </div>
    </div>