CSS Change Variables With JavaScript

CSS is the language we use to style an HTML document.
CSS describes how HTML elements should be displayed.
This tutorial will teach you CSS from basic to advanced.
Post Reply
Guest

CSS Change Variables With JavaScript

Post by Guest »

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. You can learn
more about JavaScript in our JavaScript Tutorial:

Example

<script>// Get the root elementvar r = document.querySelector(':root');
// Create a function for getting a variable valuefunction
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 valuefunction myFunction_set() {  // Set the value of
variable --blue to another value (in this case "lightblue") 
r.style.setProperty('--blue', 'lightblue');}</script>

Try it Yourself »



Browser Support
The numbers in the table specify the first browser version that fully supports the
var() function.



Function







var()
49.0
15.0
31.0
9.1
36.0




CSS var() Function


Property
Description


var()
Inserts the value of a CSS variable















+1

Reference: https://www.w3schools.com/css/css3_vari ... script.asp
Post Reply