-1

It's currently possible to get or set CSS variables from Javascript using either:

// get
getComputedStyle(document.documentElement)
    .getPropertyValue('--variable');

// set
document.documentElement.style
    .setProperty('--variable', '500px');

But in CSS I can set the style to be this:

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

@media( max-width: 800px ) {
  :root {
    --variable: "400px";
  }
}

But the JS won't re-trigger if it is only run on the first load.

Is there any way to make it trigger on events that the CSS would change the value?

Unless the page loaded in < 800px width, it would get the variable value as 1000px

markb
  • 1,100
  • 1
  • 15
  • 40

1 Answers1

0

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

Brebber
  • 2,986
  • 2
  • 9
  • 19