Skip to content

How to access CSS variables in JavaScript

Last updated on February 28, 2020

Guys, this post is really an important one as I have encountered this situation while developing my recent JavaScript application where I was in need of accessing CSS variables inside JavaScript code.

Why?

Why, to access the CSS variables inside JavaScript is that it promotes the global way of handling values thus no scattered definite values.

Let’s say if we have defined background-color with red value tobody elementin CSS whereas we would expect it to be toggled, to do this we can have one more color value to keep in JavaScript but maintaining the application this would be some what scattered instead of maintaining all values in one place.

Use-case

As said before, This post is evolved from my recent work on building one web app where I had to do Survey form feature with validation.

As we all know, Form validation typically would require us either to highlight the input field if user entered input is invalid or toggling error message or both.

To achieve this, I have done as below.

// styles.css
:root {
  --success: green;
  --error: red;
}
// index.js
function showError(input, message = 'Input is Invalid!') {
  const styles = getComputedStyle(document.documentElement);
  const color = styles.getPropertyValue('--error');
  input.style.border = `2px solid ${color}`;
  input.innerText = message;
}

Here documentElement represents css :rootselector and getComputedStylewould return you the defined css variables inside styles variable. From there we can retrieve the required value and manipulate the respective HTML element via JavaScript.

The above code is only considered for error handling not success one. If you want to try it out yourself. If you need help ping me out in the comments section.

The above piece of code snippet is taken from my work.

References

Published inFrameworksJavaScriptReact