![]()
Using CSS Variables Dynamically with jQuery
Introduction to CSS Variables and jQuery
CSS variables, also known as Custom Properties, allow developers to define reusable values in stylesheets. These variables enhance the maintainability and flexibility of CSS code. When combined with jQuery, CSS variables can be dynamically manipulated, leading to powerful and interactive user interfaces.
In this comprehensive guide, we will cover:
- What CSS variables are
- How to define CSS variables
- Manipulating CSS variables dynamically using jQuery
- Practical examples of dynamic styling
- Advanced use cases
- Best practices for performance and efficiency
1. Understanding CSS Variables
CSS variables are defined using the -- prefix and are scoped to the elements they are declared in. They are typically defined inside the :root selector to make them globally accessible.
Syntax:
:root {
--primary-color: #3498db;
--secondary-color: #2ecc71;
--font-size: 16px;
}
To use a CSS variable, we use the var() function:
body {
background-color: var(--primary-color);
font-size: var(--font-size);
}
Why Use CSS Variables?
- Maintainability: Change a single value to affect multiple elements.
- Theming: Easily switch between themes.
- Dynamic Updates: Modify styles without editing CSS files.
2. Changing CSS Variables with jQuery
Unlike standard CSS properties, CSS variables reside in the style attribute of elements or in the documentElement (root HTML node). jQuery provides easy ways to update these dynamically.
How to Modify CSS Variables with jQuery
The css() method in jQuery does not work directly with CSS variables, so we use JavaScript’s setProperty() function instead.
Basic Syntax in jQuery
$("html").get(0).style.setProperty("--primary-color", "#e74c3c");
This changes --primary-color dynamically.
3. Practical Examples
Example 1: Changing Theme Colors Dynamically
HTML
<button id="change-theme">Change Theme</button>
CSS
:root {
--primary-bg: #ffffff;
--primary-text: #000000;
}
body {
background-color: var(--primary-bg);
color: var(--primary-text);
transition: background 0.3s, color 0.3s;
}
jQuery
$("#change-theme").on("click", function () {
let root = document.documentElement;
let currentBg = getComputedStyle(root).getPropertyValue("--primary-bg").trim();
if (currentBg === "#ffffff") {
root.style.setProperty("--primary-bg", "#1e1e1e");
root.style.setProperty("--primary-text", "#ffffff");
} else {
root.style.setProperty("--primary-bg", "#ffffff");
root.style.setProperty("--primary-text", "#000000");
}
});
What Happens?
- On clicking the button, the background color switches between light and dark mode.
getComputedStyle()retrieves the current value of the variable.setProperty()modifies the CSS variable dynamically.
Example 2: Dynamic Font Size Adjustment
HTML
<input type="range" id="font-size-slider" min="12" max="30" value="16">
<p id="text">Adjust my font size!</p>
CSS
:root {
--font-size: 16px;
}
#text {
font-size: var(--font-size);
}
jQuery
$("#font-size-slider").on("input", function () {
let newSize = $(this).val() + "px";
document.documentElement.style.setProperty("--font-size", newSize);
});
What Happens?
- The slider allows users to change text size dynamically.
- The
--font-sizeCSS variable is updated when the user moves the slider.
Example 3: Creating a Custom Color Picker
HTML
<input type="color" id="color-picker">
<div class="box">Dynamic Background</div>
CSS
:root {
--box-bg: #f1c40f;
}
.box {
width: 200px;
height: 200px;
background-color: var(--box-bg);
display: flex;
align-items: center;
justify-content: center;
text-align: center;
font-weight: bold;
color: #fff;
}
jQuery
$("#color-picker").on("input", function () {
let selectedColor = $(this).val();
document.documentElement.style.setProperty("--box-bg", selectedColor);
});
What Happens?
- When a user selects a color, the background of
.boxchanges dynamically.
4. Advanced Use Cases
4.1 Storing Theme Preferences in Local Storage
To make theme changes persist, we can store values in localStorage.
Updated jQuery
$(document).ready(function () {
let savedTheme = localStorage.getItem("theme-color");
if (savedTheme) {
document.documentElement.style.setProperty("--primary-bg", savedTheme);
}
$("#change-theme").on("click", function () {
let newColor = "#1e1e1e";
let currentColor = getComputedStyle(document.documentElement).getPropertyValue("--primary-bg").trim();
if (currentColor === "#1e1e1e") {
newColor = "#ffffff";
}
document.documentElement.style.setProperty("--primary-bg", newColor);
localStorage.setItem("theme-color", newColor);
});
});
What Happens?
- The selected theme is saved in
localStorageand retrieved when the page reloads.
4.2 Animating Theme Transitions
To enhance UI aesthetics, CSS transitions can smooth theme changes.
CSS
:root {
--primary-bg: #ffffff;
}
body {
transition: background-color 0.5s ease-in-out;
}
- Now, when we change the background color dynamically, it will animate smoothly.
5. Best Practices for Using jQuery with CSS Variables
- Use
document.documentElementfor global variablesdocument.documentElement.style.setProperty("--color", "blue"); - Avoid directly modifying inline styles unless necessary
- Store values in
localStoragefor persistence - Use
getComputedStyle()to retrieve current variable values - Ensure accessibility when changing colors dynamically
- Optimize performance by limiting DOM updates
Using CSS variables dynamically with jQuery opens up endless possibilities for interactive UI enhancements. From theme switching to real-time user customization, jQuery provides an easy way to manipulate CSS properties without modifying stylesheets manually.
By leveraging jQuery’s event handling and JavaScript’s setProperty() method, you can create powerful, flexible, and interactive UI components that enhance the user experience.
Further Reading
Would you like me to add a project-based tutorial or expand on specific advanced use cases?
