Search code examples
javascriptcsscss-variables

Getting and Setting CSS Variables using JavaScript?


This week I discovered the glory of CSS3 variables! Love them!

:root {
    --main-height: 45px;
    --main-gutter: -8px;

    --match-width: 180px;
    --player-width: 370px;
    --score-width: 60px;
}

My question... is there a way I can get/set these variables in JavaScript?


Solution

  • There's a working demo here CODEPEN and the Snippet below. Details are commented in the source.

    The key parts are:

    setProperty and template literals

    // Collect the inputs
    const adjGrp = [].slice.call(document.querySelectorAll('#adjustments input'));
    
    // Add an eventListener to each input for the change event
    adjGrp.forEach(input => input.addEventListener('change', adjCSS));
    
    // Event handler uses setProperty method and template literal of the CSS variable 
    // Input name attributes are referenced to the corresponding CSS variable
    function adjCSS(e) {
      document.documentElement.style.setProperty(`--${this.name}`, this.value + 'px');
    }
    :root {
      --mainh: 45px;
      --mainw: 480px;
      --match: 180px;
      --player: 370px;
      --score: 60px;
    }
    #main {
      font: 500 16px/1.5 Consolas;
      height: var(--mainh);
      width: var(--mainw);
    }
    #scoreboard {
      display: table;
      width: calc(var(--player) + 150px);
      height: calc((var(--main) * .2));
      margin: 15px 0 15px 20px;
    }
    legend {
      font-size: 1.6rem;
      font-variant: small-caps;
    }
    output {
      display: table-cell;
      line-height: 1.5;
      border: 3px inset grey;
      padding: 3px 5px;
    }
    #match {
      width: var(--match);
    }
    #player {
      width: var(--player);
    }
    #score {
      width: var(--score);
    }
    #adjustments {
      margin: 0 0 0 20px;
    }
    <form id='main'>
      <fieldset id='scoreboard'>
        <legend>Scoreboard</legend>
        <input id='m' type='hidden'>
        <input id='p' type='hidden'>
        <input id='s' type='hidden'>
    
        <label>Player
          <output id='player' for='p'>Name</output>
          <br/>
        </label>
        <label>Match&nbsp;
          <output id='match' for='m'>0</output>
          <br/>
        </label>
        <label>Score&nbsp;
          <output id='score' for='s'>0</output>
        </label>
      </fieldset>
    
    
      <fieldset id='adjustments'>
        <legend>Adjustments</legend>
        <label>Player
          <input name='player' type='number'>
        </label>
        <br/>
        <label>Match&nbsp;
          <input name='match' type='number'>
        </label>
        <br/>
        <label>Score&nbsp;
          <input name='score' type='number'>
        </label>
        <br/>
      </fieldset>
    </form>