JAVASCRIPT
Manipulating CSS Custom Properties with JavaScript
Learn to dynamically read and update CSS custom properties (variables) directly from JavaScript, allowing for powerful theme switching and responsive design control.
function setCssVariable(variableName, value, element = document.documentElement) {
element.style.setProperty(variableName, value);
}
function getCssVariable(variableName, element = document.documentElement) {
return getComputedStyle(element).getPropertyValue(variableName).trim();
}
// Example Usage:
// Assume some CSS defined, e.g., in :root or on a specific element:
// :root {
// --primary-color: #007bff;
// --text-color: #333;
// }
// .themed-div { border: 1px solid var(--primary-color); color: var(--text-color); }
// Get initial values
const initialPrimaryColor = getCssVariable('--primary-color');
const initialTextColor = getCssVariable('--text-color');
console.log(`Initial Primary Color: ${initialPrimaryColor}`); // e.g., #007bff
console.log(`Initial Text Color: ${initialTextColor}`); // e.g., #333
// Change primary color after 1 second
setTimeout(() => {
setCssVariable('--primary-color', 'rebeccapurple');
console.log('Primary color changed to rebeccapurple');
}, 1000);
// Change text color after 2 seconds (on a specific element if desired)
// For this example, let's assume we have <div id="myThemedDiv"></div>
// And want to change the text color only for that element (if --text-color is defined there)
setTimeout(() => {
setCssVariable('--text-color', 'white', document.getElementById('myThemedDiv') || document.documentElement);
console.log('Text color changed to white');
}, 2000);
// You can verify the changes by getting the value again
setTimeout(() => {
const updatedPrimaryColor = getCssVariable('--primary-color');
console.log(`Updated Primary Color: ${updatedPrimaryColor}`); // rebeccapurple
}, 3000);
How it works: This snippet illustrates how to interact with CSS Custom Properties (variables) using JavaScript. The `setCssVariable` function uses `element.style.setProperty(variableName, value)` to dynamically update a CSS variable. The `getCssVariable` function retrieves the current computed value of a CSS variable using `getComputedStyle(element).getPropertyValue(variableName)`. This technique is incredibly powerful for implementing dynamic themes, dark modes, or making responsive style adjustments without directly manipulating individual CSS properties on many elements.