How to get and set CSS Variables with JavaScript

Integrating CSS variables with JavaScript involves dynamically updating CSS properties using JavaScript. This allows for more dynamic and interactive styling on a webpage.

Defining CSS Variables

First, you define CSS variables using the -- prefix within your CSS stylesheet. For example:

:root { --primary-color: blue; --secondary-color: green; }

Accessing and Modifying CSS Variables with JavaScript

JavaScript provides methods to access and modify CSS variables through the style property of DOM elements.

Example HTML:
<div id="myElement">Hello, World!</div>
JavaScript:
// Accessing CSS Variables const element = document.getElementById('myElement'); const style = getComputedStyle(element); // Getting the value of a CSS variable const primaryColor = style.getPropertyValue('--primary-color'); console.log(primaryColor); // Outputs: blue // Setting the value of a CSS variable element.style.setProperty('--primary-color', 'red');
run this source code Browser View
Hello, World!
Full Source:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Example: Integrating CSS Variables with JavaScript</title> <style> :root { --primary-color: blue; } #myElement { background-color: var(--primary-color); padding: 20px; margin: 20px; color: white; text-align: center; border-radius: 5px; } </style> </head> <body> <div id="myElement">Hello, World!</div> <script> // Accessing CSS Variables const element = document.getElementById('myElement'); const style = getComputedStyle(element); // Getting the value of a CSS variable const primaryColor = style.getPropertyValue('--primary-color'); console.log(primaryColor); // Outputs: blue // Setting the value of a CSS variable element.style.setProperty('--primary-color', 'red'); </script> </body> </html>

Dynamic Styling Using JavaScript Events

You can use JavaScript to dynamically change CSS variables based on user interaction or other events. For instance, changing a color on button click:

Example HTML:
<button id="changeColorButton">Change Color</button> <div id="myElement">Hello, World!</div>
JavaScript:
const changeColorButton = document.getElementById('changeColorButton'); const element = document.getElementById('myElement'); changeColorButton.addEventListener('click', () => { element.style.setProperty('--primary-color', 'orange'); });
run this source code Browser View
Hello, World!
Full Source:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Example: Integrating CSS Variables with JavaScript</title> <style> :root { --primary-color: blue; } #myElement { background-color: var(--primary-color); padding: 20px; margin: 20px; color: white; text-align: center; border-radius: 5px; } #changeColorButton { padding: 10px 20px; font-size: 16px; cursor: pointer; } </style> </head> <body> <button id="changeColorButton">Change Color</button> <div id="myElement">Hello, World!</div> <script> const changeColorButton = document.getElementById('changeColorButton'); const element = document.getElementById('myElement'); changeColorButton.addEventListener('click', () => { element.style.setProperty('--primary-color', 'orange'); }); </script> </body> </html>

Animation and Transition Effects

CSS variables can also be used to create animation and transition effects. You can dynamically change the value of a CSS variable over time using JavaScript to create smooth transitions or animations.

Example CSS:
#myElement { background-color: var(--primary-color); transition: background-color 0.5s ease-in-out; }
JavaScript:
const element = document.getElementById('myElement'); // Function to toggle background color function toggleBackgroundColor() { const currentColor = getComputedStyle(element).getPropertyValue('--primary-color'); const newColor = currentColor === 'blue' ? 'red' : 'blue'; element.style.setProperty('--primary-color', newColor); } // Toggle background color every 2 seconds setInterval(toggleBackgroundColor, 2000);
run this source code Browser View
Hello, World!
Full Source:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Example: Integrating CSS Variables with JavaScript</title> <style> :root { --primary-color: blue; } #myElement { background-color: var(--primary-color); padding: 20px; margin: 20px; color: white; text-align: center; border-radius: 5px; transition: background-color 0.5s ease-in-out; } </style> </head> <body> <div id="myElement">Hello, World!</div> <script> const element = document.getElementById('myElement'); // Function to toggle background color function toggleBackgroundColor() { const currentColor = getComputedStyle(element).getPropertyValue('--primary-color'); const newColor = currentColor === 'blue' ? 'red' : 'blue'; element.style.setProperty('--primary-color', newColor); } // Toggle background color every 2 seconds setInterval(toggleBackgroundColor, 2000); </script> </body> </html>

Benefits of Integration

Integrating CSS variables with JavaScript offers several benefits. First, it enhances maintainability by centralizing colors, fonts, and other styles in variables, making it easier to manage and update styles across the entire project. Additionally, it enables dynamic themes, allowing for easy switching between different themes or adjusting styles based on user preferences without extensive code changes. Moreover, it promotes interactivity by facilitating the creation of responsive and dynamic UI elements, enhancing the user experience. Finally, it helps in reducing code redundancy by avoiding repetitive code for common styles, leading to cleaner and more efficient codebases.

Conclusion

Integrating CSS variables with JavaScript enables dynamic and responsive styling on webpages by allowing for the manipulation of CSS properties in real-time. This integration enhances maintainability, promotes interactivity, and reduces code redundancy, providing developers with greater flexibility and efficiency in styling their web applications.