How to update CSS Variables with JS : Day 3 #JavaScript30

A small project on CSS variables

Β·

6 min read

How to update CSS Variables with JS : Day 3 #JavaScript30

πŸ‘‹ Hello people!

In this blog, we will be having a look at CSS variables and updating them with Javascript. You might have known about variables in SCSS, but they exist in CSS too. Coming to the project part of it, we will make a simple web page with an image whose spacing, blur and color around it can be updated. Check the live demo .

The starter files for this project can be found here.

🧠 HTML && CSS

The markup for this project has 2 input fields of type range and another of type color ( this will let you select a color from browser's color picker ).name attribute here should match with the CSS variable name. data-sizing attribute is for adding a suffix to values updated. More on this in Javascript section.

  <div class="controls">
    <label for="spacing">Spacing:</label>
    <input id="spacing" type="range" name="spacing" min="10" max="200" value="10" data-sizing="px">

    <label for="blur">Blur:</label>
    <input id="blur" type="range" name="blur" min="0" max="25" value="10" data-sizing="px">

    <label for="base">Base Color</label>
    <input id="base" type="color" name="base-color" value="#BADA55">
  </div>

That's pretty much the important part of HTML we would be needing.

In CSS we declare variables in :root level

:root{
  --base-color: #BADA55;
  --spacing : 0px;
  --blur: 0px;
}

The declared variables are later attached to the img and hl element. In img element , updating --spacing element will make changes to padding around the image. Similarly, background and filter properties are updated as well. When we look into the HTML part, we have a hl class as well. It updates the color in some part of heading.

img {
  padding: var(--spacing);
  filter: blur(var(--blur));
  background: var(--base-color);
}

.hl
  color: var(--base-color);
}

That's all the markup and styling we need to focus on. So far, so good.

πŸ’› JavaScript

Coming to javascript side of things, this is the crux of it. We listen to the changes in the input fields and update the variables according to them. Seems simple? yeah, it is. First, let's store all the inputs in a constant.

const inputs = document.querySelectorAll('.controls input');
console.log(inputs) //logging is just to check.

See the console.log returns a NodeList, which is quite different from an Array. The methods that can be applied on a NodeList are quite limited when compared to Array. Console log any Array and find out the difference . We will be needing forEach method, it's present. No worries there. We need to have an eventlistener , that triggers a function for updating variables, upon specific events. In our case we listen to change and mousemove events. Why mousemove event you ask. Well, try not to add that event listener and check what happens upon dragging the input bar.

inputs.forEach(inputs => inputs.addEventListener('change',varUpdate));
inputs.forEach(inputs => inputs.addEventListener('mousemove',varUpdate));

Do you see the varUpdate function over there? That updates our CSS variables. Will be defining that function now.

function varUpdate() {

    document.documentElement.style.setProperty(`--${this.name}`,this.value + suffix)
}

In the document -> documentElement -> style, we setProperty to above string. Here this.name would give the name of the input field from the NodeList we got earlier and this.value would give its value updated by the user. What's that suffix then, you ask? Before that let us see what this looks like for spacing input field:--spacing 10. That won't be enough, we need the word px after it. If you remember we gave data-sizing = px attribute in HTML. That px should be appended here for spacing and blur variables. We are almost to the end, adding this suffix gets it done. Let's look at complete Javascript now.

const inputs = document.querySelectorAll('.controls input');

function varUpdate() {
    const suffix = this.dataset.sizing || "";
    document.documentElement.style.setProperty(`--${this.name}`,this.value + suffix)
}
inputs.forEach(inputs => inputs.addEventListener('change',varUpdate));
inputs.forEach(inputs => inputs.addEventListener('mousemove',varUpdate));

Quick Recap

We have seen,

  • how to declare CSS variables
  • NodeList vs Array
  • how to update variables based upon user input
  • adding suffixes to the end of CSS variables.

Thank you for reading.

This would have helped you to get a quick understanding of CSS variables and how to update them with JS. Feel free to drop a comment, if you have found it useful. See you in my next blog. Until then,

Bye !

Further Reading

I have found this rather detailed article on FreeCodecamp about CSS variables. The course, from which the project is picked.

Β