Reputation: 25
I have the following code that I'm using to update the css variable called --changeColor
const r = document.querySelector(':root');
const currentColor = getComputedStyle(r).getPropertyValue('--changeColor');
console.log(currentColor) //logs #2c988b
function newColor() {
console.log(currentColor) //logs #2c988b
if (currentColor === '#2c988b') {
r.style.setProperty('--changeColor', '#000000');
}
}
The problem is that the code inside the if statement doesn't seem to run as I imagined it would. If the condition is changed to say 1 < 2 and I call the function in the console then the code inside the statement is executed. So my conclusion is that I'm trying something with the if statement that's not possible.
Can someone please tell me what that is and how to make it work?
Upvotes: 2
Views: 96
Reputation: 113
The problem in your code (I think) is that when you get the CSS variable with
const currentColor = getComputedStyle(r).getPropertyValue("--changeColor");
the whitespaces around the variables are kept. So you should trim() currentColor before comparing it with a string. Try if something like the following works:
https://stackblitz.com/edit/js-acyb8x
Upvotes: 2