#js30.03: CSS variables & js

This exercise demonstrated how to use javascript to get, e.g., slider and color picker inputs values, and assign them to CSS variables, thereby modifying e.g., an image element’s border, padding and background-color.

Once I completed the tutorial according to the accompanying video, I added an image selector and a function to randomly select an image to display on load. [ see ‘Update CSS Variables with JS’ here. ]

Here are the broad strokes: first, set up some CSS variables [TO-DO: why on :root? ]:


<style>
   :root   {
      /* the input 'name' property must match the css variable */
      --color1: #bada55;
      --color2: lime;
      --spacing: .3rem;
      --border-width: 3px;
      --blur: 0;
   }

/* … and the only other relevant CSS: */
   img   {
      padding: calc(1 * var(--spacing));
      background: var(--color1);
      border: var(--border-width) var(--border-style) var(--border-color);
      -webkit-filter: blur(var(--blur));
   }
</style>

… and the markup:


<div class="controls">
   <!-- the input 'name' property must match the css variable -->
   <label for="color1">background color</label>
   <input type="color" name="color1" value="#ffffff" />
   <label for="color2">border color</label>
   <input type="color" name="color2" value="#ffffff" />
   <label for="spacing">Padding:</label>
   <input type="range" name="spacing" min="3" max="45" value="15" data-sizeunit="px" data-drummer="buddy" />
   <label for="border-width">border width</label>
   <input type="range" name="border-width" min="3" max="45" value="15" data-sizeunit="px" />
   <label for="blur">Blur:</label>
   <input type="range" name="blur" min="0" max="30" value="0" data-sizeunit="px" />

... and finally the javascript:


   const inputs = document.querySelectorAll('.controls input, .controls select ');
   const selector = document.querySelector('select');
   const img = document.querySelector('img');

   // randomly select an initial image:
   var random = function() {
      var min = 0;
      var max = selector.length-1; // # of option elements, -1
      var randomVal = Math.floor(Math.random() * (max - min + 1)) + min;
      return randomVal;
   };

   function setInitImg() {
      var randomVal = random();
      const initImgSrc = selector.options[randomVal].value;
      selector[randomVal].selected = "selected";
      img.src = initImgSrc;
   };
   setInitImg();

   inputs.forEach(input => input.addEventListener('change', updateValues));
   
   function updateValues() {
      const suffix = this.dataset.sizeunit || '';
      const selectedImg = selector.options[selector.selectedIndex].value;
      img.src = selectedImg;
      document.documentElement.style.setProperty(`--${this.name}`, this.value+suffix);
   }