Open Playground
CSS AdvancedLesson #168

Variables and JavaScript

CSS variables have access to the DOM, which means that you can change them 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 --primary-bg-color 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

Example Code

html
Try it Yourself
<script>
// Get the root element
var r =
  document.querySelector(':root');

// 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 --primary-bg-color variable
  alert("The value
  of --primary-bg-color is: " + rs.getPropertyValue('--primary-bg-color'));
}

// Function for setting a variable value
function myFunction_set() {

  // Set the value of variable --primary-bg-color to another value (in this case
  "green")
  r.style.setProperty('--primary-bg-color', 'green');
}

  </script>

CSS var() Function

FunctionDescription
var()Inserts the value of a CSS variable


Interactive Code Examples

CSS Example 1

html
Try it Yourself
CSS syntax and property demonstration.
<script>
// Get the root element
var r = 
  document.querySelector(':root');

// 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 --primary-bg-color variable
  alert("The value 
  of --primary-bg-color is: " + rs.getPropertyValue('--primary-bg-color'));
}

  
// Function for setting a variable value
function myFunction_set() {
  
  // Set the value of variable --primary-bg-color to another value (in this case 
  "green")
  r.style.setProperty('--primary-bg-color', 'green');
}

  </script>