I am attempting to get the value of a CSS variable in my JavaScript code. I am using the following code snippet to achieve this. In this case I am getting a certain shade of red I defined in my CSS.
let red = getComputedStyle(document.documentElement).getPropertyValue('--red')
The issue is that this code only works when I wrap it in a setTimeout
block shown below,
setTimeout(() => {
let red = getComputedStyle(document.documentElement).getPropertyValue('--red')
}, 10)
So the JavaScript seems like it needs to wait for a moment for the CSS to finish loading. Is there a way to get the value of CSS variables without having to wait an explicit amount of time like I have shown above?
Also I discovered that I do not need the setTimout when I run my app through the VS Code Live Server extension but I do need to use when I open the HTML file through my File Explorer.