How to Get a CSS Variable with JavaScript and Set One Too
While working on a redesign, I needed a way for JavaScript to get the value of a CSS variable to determine the state of a page. Lucky for us, there is a browser compatible and easy method.
It's common to see global root level variables used.
:root {
--display-moon: none;
}
I prefer to use a utility CSS framework these days like Tailwind that sets my global properties. I then set component level variables to keep my scope limited.
.hero-wrapper {
--display-moon: none;
}
In my case, I was using a combination of the prefers-color-scheme and class selectors to set variables based on whether the user wanted a dark or light theme. With prefers-color-scheme, the user's browser can set the default when the page loads. I needed a way to know what the browser defaulted to. Since I was showing a moon SVG on dark mode, I could look at the variable I had attached to the moon.
With JavaScript, it's easy to query an element's CSS variables.
getComputedStyle(document.querySelector('.hero-wrapper'))
.getPropertyValue('--display-moon');
I could use this to set a variable that tells me the initial state by checking to see if the CSS variable is none
or block
.
const initialDarkMode =
getComputedStyle(document.querySelector('.hero-wrapper'))
.getPropertyValue('--display-moon') === 'block';
If I had my variables set to the root instead of an HTML element, the code would be similar but without the querySelector.
const initialDarkMode =
getComputedStyle(document.documentElement)
.getPropertyValue('--display-moon') === 'block';
In my case, JavaScript never needs to set the CSS variable. If I ever needed to set a CSS variable that's easy too.
document.documentElement.style
.setProperty('--display-moon', 'none');
A root element can use the document.documentElement. With an HTML element, use the document.querySelector or a different element selector method.
One Last Thing...
If you have a question or see a mistake, please comment below.
If you found this post helpful, please share it with others. It's the best thanks I can ask for & it gives me momentum to keep writing!