0

I have css variables defined within a css class.

.popup {
    --popup-opacity: 0;
    --popup-visibility: hidden;
    opacity: var(--popup-opacity);
    visibility: var(--popup-visibility);
}

I want to update this using javascript. The following code works if variables are within root element:

 document.documentElement.style.setProperty('--popup-opacity', 1);
 document.documentElement.style.setProperty('--popup-visibility', 'visible');

I cannot figure out how to make it work when variables are defined within the css class. Please help.

Uttam Nandi
  • 117
  • 1
  • 3
  • 10
  • Refer to this https://stackoverflow.com/questions/36088655/accessing-a-css-custom-property-aka-css-variable-through-javascript – Debsmita Paul Nov 02 '20 at 11:50

1 Answers1

1

This is how inheritance in JS works.

If you've set the value of the variable in the rule-set with the class selector then that element won't inherit from higher up the DOM.

It's the same issue you would get if you set .popup { color: red; } and then wondered why it remains red is you set document.documentElement.style.setProperty('color', "red");

Define your variables higher up the DOM:

html {
    --popup-opacity: 0;
    --popup-visibility: hidden;
}

.popup {
    opacity: var(--popup-opacity);
    visibility: var(--popup-visibility);
}

and then override them at the same level or one between it and where they are read:

 document.body.style.setProperty('--popup-opacity', 1);
 document.body.style.setProperty('--popup-visibility', 'visible');
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335