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.

1

1 Answer 1

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');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.