Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Get and Set CSS Variables with JavaScript
To get and set CSS variables with JavaScript, we can use various methods. The getComputedStyle() method gives an object which includes all the styles applied to the target element. The getPropertyValue() method is used to obtain the desired property from the computed styles. The setProperty() method is used to change the value of CSS variable.
Syntax
/* Getting CSS Variable */
getComputedStyle(element).getPropertyValue('--variable-name');
/* Setting CSS Variable */
element.style.setProperty('--variable-name', 'value');
Methods Used
| Method | Purpose |
|---|---|
getComputedStyle() |
Returns computed styles of an element |
getPropertyValue() |
Gets the value of a specific CSS property |
setProperty() |
Sets the value of a CSS property |
Example: Toggle Background Color
The following example demonstrates how to get and set CSS variables with JavaScript by toggling the background color of a div upon clicking a button −
<!DOCTYPE html>
<html>
<head>
<style>
:root {
--custom-bg-color: #8a1515;
}
.container {
display: flex;
justify-content: center;
align-items: center;
height: 200px;
background-color: var(--custom-bg-color);
transition: background-color 0.3s ease;
}
button {
padding: 15px 30px;
font-size: 18px;
cursor: pointer;
background-color: white;
border: 2px solid #333;
border-radius: 5px;
}
</style>
</head>
<body>
<div class="container">
<button onclick="toggleTheme()">Change Theme</button>
</div>
<script>
function toggleTheme() {
const root = document.documentElement;
// Get current value of CSS variable
const currentColor = getComputedStyle(root)
.getPropertyValue('--custom-bg-color').trim();
// Toggle between colors
if (currentColor === '#8a1515') {
root.style.setProperty('--custom-bg-color', '#2c3e50');
} else {
root.style.setProperty('--custom-bg-color', '#8a1515');
}
}
</script>
</body>
</html>
A red container with a "Change Theme" button appears. Clicking the button toggles the background between red (#8a1515) and dark blue (#2c3e50) with a smooth transition effect.
Key Points
- CSS variables are declared using the
--prefix in the:rootselector for global scope - Use
getComputedStyle()to access computed styles of any element - The
.trim()method removes whitespace from the retrieved value - CSS variables can be updated dynamically, affecting all elements that use them
Conclusion
Getting and setting CSS variables with JavaScript provides powerful dynamic styling capabilities. Use getPropertyValue() to retrieve current values and setProperty() to update them, enabling interactive theme changes and responsive designs.
