Access CSS Variable from JavaScript

Access CSS variable from javascript

Just the standard way:

  1. Get the computed styles with getComputedStyle
  2. Use getPropertyValue to get the value of the desired property
getComputedStyle(element).getPropertyValue('--color-font-general');

Example:

var style = getComputedStyle(document.body)
console.log( style.getPropertyValue('--bar') ) // #336699
console.log( style.getPropertyValue('--baz') ) // calc(2px*2)
:root { --foo:#336699; --bar:var(--foo); --baz:calc(2px*2); }

Get CSS variable in JS on change, resizing, or media-quiries

Question 1: getting only one value

At the moment your JS indeed only get 1000px as value for the variable because there is a huddle in your CSS.

In media queries you have to advise the variable to element :root either. Without advising a variable to an element it does not work. Try:


// CSS
// --> in media queries advice settings to elements

:root {
--variable: "1000px";
}



@media (max-width: 800px) {
/* use correct css */
:root {
--variable: "400px";
}
}



Question 2: trigger events in JS to get values

Yes. You are able to trigger events and execute your code. Here is an example to do it when the window resize:


// JAVASCRIPT
// --> when window resize
// --> read css variable and show value in console

window.addEventListener('resize', function(){
let value_var = getComputedStyle(document.documentElement).getPropertyValue('--variable');
console.log(value_var);
});


More information about triggering events in JS: https://www.w3schools.com/js/js_events.asp

Accessing a CSS custom property (aka CSS variable) through JavaScript

You can use document.body.style.setProperty('--name', value);:

var bodyStyles = window.getComputedStyle(document.body);
var fooBar = bodyStyles.getPropertyValue('--foo-bar'); //get

document.body.style.setProperty('--foo-bar', newValue);//set

More Information here.

How can I create CSS variables with JavaScript?

Yes, you can do it via .setProperty() method:

const root = document.documentElement;
root.style.setProperty('--first-color', 'red');
root.style.setProperty('--second-color', 'blue');
p {
color: var(--first-color);
}

div {
color: var(--second-color);
}
<p>First color</p>
<div>Second color</div>

Accessing css variable in JS file

Assuming you're using native CSS variables and not some preprocessor, take a look at this page. At the bottom there's a section called Values in JavaScript which describes how to access native CSS vars in JS code.

getComputedStyle(element).getPropertyValue("--my-var");

However if you are using a CSS preprocessor, it is not possible to retrieve the variables via JS since they're already processed in the build process.

How can I change CSS variable on button click?

You are trying to change the value of one variable with another variable.

You will need getComputedStlye():