CSS variables but with a dash of JavaScript. ✨
Tags: javascript, css, tutorial, webdev
Published: 2020-11-06 09:04:20

Okay, we'll go with this quick and straight. When you first start diving into CSS, you do the usual thing like changing color, changing fonts, etc. Then you dive deep into media queries, cross-browser properties, and finally to variables. 

But what if we use these variables in our CSS files alongside with some magic of our old friend JavaScript, then imagine what we can achieve! Something cool? Yes, you're correct. Let's do this and make something nice.

![Sprinkle GIF](https://media.giphy.com/media/l0IyeRaKu4ikJYE1O/giphy.gif)
<figcaption>Something to sprinkle!</figcaption>

---

# Quick note on CSS variables 📝

Of course, some basics first. 

> **CSS Custom Properties** or **CSS Variables** allows us to store a value stored in one place, then referenced in multiple other places. 

Sometimes specific values need to be reused throughout a document. A typical example is when you get a specific color palette from designers, and you need to add specific hex values of colors, font-sizes, or even some responsive breakpoints. You assign these values to your custom-made CSS properties called variables here. 

This is useful not only because they can be used at multiple instances and makes editing the values easy but also, it makes the properties easier to read when referring to it later. For example: `--headline-color` is better to read than `#000`.

Check out this wonderful CodePen example:

{% codepen https://codepen.io/jdsteinbach/pen/AeEwk default-tab=css,result %}

### Usage and syntax 

Declaring a custom CSS property is created by assigning the double hyphen (`--`) in front of the variable name, and then the property value is written like any other CSS property. 

Check out this example:

```css
element {
  --main-bg-color: lightgray;
}
```
Now, to use this custom property anywhere in your CSS file you can do this:

```css
element {
  background-color: var(--main-bg-color);
}
```

So, you don't need to write `lightgray` value for the background-color in all places where there is a need to use the `var()` function and pass in the CSS custom variable inside. 

# Introducing JavaScript ✨

Time to start interacting with the web developer's favorite language.

Let's see how we can write a new property value in JavaScript.

### ➡️ `setProperty`

```js
var element = document.documentElement;
element.style.setProperty('--name', value);
```

So, what these new functions mean? 

- [`document.documentElement`](https://developer.mozilla.org/en-US/docs/Web/API/Document/documentElement): this returns the [`Element`](https://developer.mozilla.org/en-US/docs/Web/API/Element) which is usually the root element of your HTML document.

- [`style.setProperty()`](https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/setProperty): it sets a new value for a property on a CSS style declaration object.

The `setProperty()` takes in the _property name_, it's _value_, and optionally the _priority_.

The code you saw above sets a new value for a globally defined property. This type of JavaScript code is useful when you are managing state and then modifying CSS styles based on given values.

### ➡️ `getPropertyValue`
 
```js
element.style.getPropertyValue('--my-color');
```

Yeah, exactly what you're thinking right now. Just as with any other language, we have setters and getters here too. With the `setProperty` we were _setting_ a new value, and here with [`getPropertyValue`](https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/getPropertyValue), we return a [`DOMString`](https://developer.mozilla.org/en-US/docs/Web/API/DOMString) containing the value of the above-specified CSS property.

Here's a practical example:

```js
element.style.setProperty('--accent-color', '#663399');
element.style.getPropertyValue('--accent-color');
```

This will return the value of `--accent-color` as `#663399` when the browser renders the webpage.

### ➡️ `removeProperty`

```js
element.style.removeProperty('--my-color');
```

The [`removeProperty`](https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/removeProperty) method will remove the provided property from a CSS style declaration object.

So, if you want to dynamically remove the attached custom CSS property, then you can have code similar to this:

```js
element.style.setProperty('--accent-color', '#663399');
element.style.getPropertyValue('--accent-color');

element.style.removeProperty('--accent-color');
```

# Using event listeners 👂

If there's some JavaScript code, then there are events happening! What if you want to change a `div`'s position on cursor click?

First, start off with declaring the CSS variables:

```css
:root {
  --cursor-pos-x: 10px;
  --cursor-pos-y: 10px;
}
```

By declaring them at [`:root`](https://developer.mozilla.org/en-US/docs/Web/CSS/:root), we're putting them into the _root_ element of the DOM tree. Typically, it's the `<html>` element.

Next, we will be using these variables in our `<div>` as follows:

```css
div {
  .
  .
  .
  left: var(--cursor-pos-x);
  top: var(--cursor-pos-x;
  .
  .
  .
}
```

As you know by now, it translates into:

```css
 div {
  .
  .
  .
  left: 10px;
  top: 10px;
  .
  .
  .
}
```

We have set the initial position of the `<div>`, now let's interact with an event listener.

```js
let root = document.documentElement;

root.addEventListener('click', event => {
  root.style.setProperty('--cursor-pos-x', event.clientX + "px");
  root.style.setProperty('--cursor-pos-y', event.clientY + "px");
});
```

We are simply using the [`clientX`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/clientX) and [`clientY`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/clientY) properties of the [`MouseEvent`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent) interface, whose function is to move the corresponding `div` in both _X_ and _Y_ directions, respectively.

The result will be similar to this:

![Mouse click demo](https://dev-to-uploads.s3.amazonaws.com/i/299j5nwbpae0hdy9c2hi.gif)

That is it! There are endless possibilities when it comes to combining the power of CSS variables with JavaScript. You can make awesome DOM-based games, use it to change component styles dynamically, and more!

# More resources 🤩

Go ahead and learn more about custom CSS properties from the resources given below:

- 📄 [MDN CSS Custom Properties docs](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties) 
- [CSS Tricks - Making Custom Properties more dynamic](https://css-tricks.com/making-custom-properties-css-variables-dynamic/
)
- [Reactive Animations with CSS Variables by David Khourshid](https://slides.com/davidkhourshid/reactanim)
- [Communicating Between JavaScript and CSS Using CSS Variables by Zack Bloom](https://eager.io/blog/communicating-between-javascript-and-css-with-css-variables/)

</hr>

_Thanks for reading. I appreciate it! Have a good day. (✿◕‿◕✿)_

</hr>
<blockquote class="twitter-tweet" data-partner="tweetdeck"><p lang="en" dir="ltr">Team printf!<a href="https://twitter.com/hashtag/programmingmemes?src=hash&amp;ref_src=twsrc%5Etfw">#programmingmemes</a> <a href="https://twitter.com/hashtag/DEVCommunity?src=hash&amp;ref_src=twsrc%5Etfw">#DEVCommunity</a> <a href="https://t.co/Ou4sNRPRE7">pic.twitter.com/Ou4sNRPRE7</a></p>&mdash; 🎵PhonoForest🌳GameDev🎮 (@PhonoForest) <a href="https://twitter.com/PhonoForest/status/1321483031627137024?ref_src=twsrc%5Etfw">October 28, 2020</a></blockquote>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

<hr/>
_[daily.dev](https://api.daily.dev/get?r=devto) delivers the best programming news every new tab. We will rank hundreds of qualified sources for you so that you can hack the future._
[![Daily Poster](https://dev-to-uploads.s3.amazonaws.com/i/b996k4sm4efhietrzups.png)](https://api.daily.dev/get?r=devto)