CSS Change Variables With JavaScript
Change Variables With JavaScript
CSS variables have access to the DOM, which means that you can change them with JavaScript.
Here is an example of how you can create a script to display and change the --blue variable from the example used in the previous pages. For now, do not worry if you are not familiar with JavaScript.
<script>
// Get the root element
var r = document.querySelector(':root');
// Create a function for getting a variable value
function myFunction_get() {
// Get the styles (properties and values) for the root
var rs = getComputedStyle(r);
// Alert the value of the --blue variable
alert("The value of --blue is: " + rs.getPropertyValue('--blue'));
}
// Create a function for setting a variable value
function myFunction_set() {
// Set the value of variable --blue to another value (in this case "lightblue")
r.style.setProperty('--blue', 'lightblue');
}
</script>