Computer >> Computer tutorials >  >> Programming >> Javascript

Get and Set CSS Variables with JavaScript


The getComputedStyle() method gives an object which includes all the styles applied to the target element. getPropertyValue() method is used to obtain the desired property from the computed styles. setProperty() is used to change the value of CSS variable.

Example

The following examples illustrate how we can get and set CSS variables using JavaScript.

<!DOCTYPE html>
<html>
<head>
<style>
:root {
   --outerColor: magenta;
   --innerColor: lightgreen;
   text-align: center;
}
div {
   margin: 5%;
   padding: 10%;
   background-color: var(--innerColor);
   border: 2px groove var(--outerColor);
}
</style>
</head>
<body>
<div onmouseover="showColor()" onmouseout="changeColor()">
<p></p>
</div>
</body>
<script>
let ele = document.querySelector(':root');
let para = document.querySelector('p');
function showColor() {
   let cs = getComputedStyle(ele);
   para.textContent = ("Previously " + cs.getPropertyValue('--innerColor') + " color");
}
function changeColor() {
   let item = document.querySelector('div');
   item.style.setProperty('--innerColor', 'magenta')
}
</script>
</html>

Output

This will produce the following result −

Get and Set CSS Variables with JavaScript

Example

<!DOCTYPE html>
<html>
<head>
<style>
:root {
   --customColor: seagreen;
}
div {
   margin: 5%;
   width: 130px;
   height: 130px;
   box-shadow: inset 0 0 38px var(--customColor);
   border-radius: 50%;
}
</style>
</head>
<body>
<div onmouseover="toggle()"></div>
</body>
<script>
let ele = document.querySelector(':root');
function toggle() {
   let cs = getComputedStyle(ele);
   let item = document.querySelector('div');
   if(cs.getPropertyValue('--customColor') !== 'blue') {
      item.style.setProperty('--customColor', 'blue')
   }
}
</script>
</html>

Output

This will produce the following result −

Get and Set CSS Variables with JavaScript