I have these CSS variables to control the colors of my project so I can do theming.
html { --main-background-image: url(../images/starsBackground.jpg); --main-text-color: #4CAF50; --main-background-color: rgba(0,0,0,.25); --beta-background-color: rgba(0,0,0,.85); }
However no matter how I try to change the attribute(the two commented lines tried separately), the closest I get is returning not a valid attribute.
function loadTheme() { var htmlTag = document.getElementsByTagName("html"); var yourSelect = document.getElementById( "themeSelect" ); var selectedTheme = ( yourSelect.options[ yourSelect.selectedIndex ].value ); // htmlTag[0].setAttribute('--main-text-color', '#FFCF40'); // $("html").css("--main-text-color","#FFCF40"); }
With JavaScript, we are able to set CSS styles for one or multiple elements in the DOM, modify them, remove them or even change the whole stylesheet for all your page.
CSS variables have access to the DOM, which means that you can change them with JavaScript.
Setting a CSS Variable's Value To set the value of a CSS variable using JavaScript, you use setProperty on documentElement 's style property: document. documentElement. style .
To declare a variable in CSS, come up with a name for the variable, then append two hyphens (–) as the prefix. The element here refers to any valid HTML element that has access to this CSS file. The variable name is bg-color , and two hyphens are appended.
Turns out changing CSS variables is possible using the el.style.cssText
property, or el.style.setProperty
or el.setAttribute
methods. In your code snippets el.setAttribute
is incorrectly used, which is causing the error you encountered. Here's the correct way:
document.documentElement.style.cssText = "--main-background-color: red";
or
document.documentElement.style.setProperty("--main-background-color", "green");
or
document.documentElement.setAttribute("style", "--main-background-color: green");
Demo
The following demo defines a background color using a CSS variable, then changes it using the JS snippet 2 seconds after loading.
window.onload = function() { setTimeout(function() { document.documentElement.style.cssText = "--main-background-color: red"; }, 2000); };
html { --main-background-image: url(../images/starsBackground.jpg); --main-text-color: #4CAF50; --main-background-color: rgba(0,0,0,.25); --beta-background-color: rgba(0,0,0,.85); } body { background-color: var(--main-background-color); }
This will only work in browsers supporting CSS variables obviously.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With