Variables and JavaScript

CSS variables can be dynamically updated using JavaScript, allowing you to create interactive and adaptable styles based on user interactions or events. This is achieved by accessing and modifying the CSS custom properties directly on the documentElement.

Key Topics

Dynamic Updates

CSS variables can be updated dynamically using JavaScript's setProperty method on the style property of the document.documentElement.

<style>
        :root {
            --bg-color: #007BFF;
        }
        body {
            background-color: var(--bg-color);
        }
</style>
<button onclick="changeBackgroundColor('#FF5733')">Change Background Color</button>
<script>
    function changeBackgroundColor(color) {
        document.documentElement.style.setProperty('--bg-color', color);
    }
</script>

Explanation: Clicking the button updates the --bg-color variable, dynamically changing the background color of the page.

Interactive Design

CSS variables and JavaScript can work together to create interactive designs that respond to user input.

<style>
        :root {
            --font-size: 16px;
        }
        body {
            font-size: var(--font-size);
        }
</style>
<input type="range" min="10" max="30" value="16" oninput="changeFontSize(this.value)">
<script>
    function changeFontSize(size) {
        document.documentElement.style.setProperty('--font-size', size + 'px');
    }
</script>

Explanation: Moving the slider dynamically updates the --font-size variable, changing the font size of the page in real-time.

Retrieving CSS Variable Values

You can retrieve the current value of a CSS variable using the getComputedStyle method in JavaScript.

<style>
        :root {
            --text-color: #007BFF;
        }
        .text {
            color: var(--text-color);
        }
</style>
<div class="text">Sample Text</div>
<button onclick="logTextColor()">Log Text Color</button>
<script>
    function logTextColor() {
        const textColor = getComputedStyle(document.documentElement).getPropertyValue('--text-color');
        console.log('Current text color:', textColor);
    }
</script>

Explanation: Clicking the button retrieves the value of --text-color and logs it to the console.

Key Takeaways

  • Dynamic Updates: Use setProperty to dynamically change the values of CSS variables.
  • Interactive Designs: Combine CSS variables with JavaScript to create responsive and adaptable designs.
  • Retrieving Values: Access the current value of a CSS variable with getComputedStyle.
  • Flexibility: Dynamically updating CSS variables simplifies real-time styling and theming.
  • Enhanced Interactivity: JavaScript provides seamless integration with CSS for interactive UI elements.