0Pricing
CSS Academy · Lesson

Updating Variables with JavaScript

Dynamically update CSS custom properties from JavaScript using style.setProperty().

Updating Variables with JavaScript is a free CSS Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the CSS Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Why Update CSS Variables from JS?

CSS custom properties are live in the browser. Changing them via JavaScript immediately updates all elements using that property — enabling dynamic themes, real-time sliders, and state-driven styles without toggling many classes.

Getting a Custom Property Value

Read a custom property value using getComputedStyle():

const root = document.documentElement;
const value = getComputedStyle(root)
  .getPropertyValue('--primary-color').trim();
console.log(value); // '#3b82f6'

Setting a Custom Property Value

Update a custom property using style.setProperty() on any element:

// Set globally on :root
document.documentElement.style.setProperty('--primary-color', '#ef4444');

// Set on a specific element
document.querySelector('.card').style.setProperty('--card-bg', 'pink');

Removing a Custom Property

Remove a property override (revert to CSS-declared value) using style.removeProperty():

document.documentElement.style.removeProperty('--primary-color');
// Now the :root CSS value applies again

Theme Switcher Pattern

A classic theme switcher that swaps a data-theme attribute and defines variables per theme in CSS:

// JavaScript
document.body.dataset.theme = 'dark';

// CSS
[data-theme='dark'] {
  --bg: #111;
  --text: #eee;
}

Progress Bar with CSS Variable

Drive a progress bar value entirely via a CSS variable set from JavaScript:

// CSS
.progress-bar {
  width: var(--progress, 0%);
  transition: width 300ms ease;
  height: 8px;
  background: royalblue;
}

// JS
function setProgress(pct) {
  document.querySelector('.progress-bar')
    .style.setProperty('--progress', pct + '%');
}

Mouse Position Tracking

Create parallax or cursor-following effects by updating positional CSS variables on mouse move:

document.addEventListener('mousemove', e => {
  document.documentElement.style.setProperty('--mouse-x', e.clientX + 'px');
  document.documentElement.style.setProperty('--mouse-y', e.clientY + 'px');
});

Scroll-Driven Variables

Update a CSS variable based on scroll position for scroll-linked animations (modern APIs handle this better, but JS+variable is still a simple approach):

window.addEventListener('scroll', () => {
  const pct = window.scrollY / (document.body.scrollHeight - window.innerHeight);
  document.documentElement.style.setProperty('--scroll', pct);
});

User Preferences with localStorage

Save the selected theme to localStorage and restore it on page load:

// Restore
const saved = localStorage.getItem('theme') || 'light';
document.documentElement.dataset.theme = saved;

// Toggle
function toggleTheme() {
  const next = document.documentElement.dataset.theme === 'dark' ? 'light' : 'dark';
  document.documentElement.dataset.theme = next;
  localStorage.setItem('theme', next);
}

CSS vs JS Animations

For smooth animations, prefer CSS transitions that react to custom property changes rather than JS requestAnimationFrame loops. The browser handles interpolation on the compositor thread.

Typed Properties with @property

Registering a variable with @property allows browsers to interpolate it in transitions — something that does not work with unregistered custom properties:

@property --progress {
  syntax: '<percentage>';
  inherits: false;
  initial-value: 0%;
}

.bar {
  --progress: 0%;
  width: var(--progress);
  transition: --progress 500ms;
}

Quick Check

Which JavaScript method changes a CSS custom property on the root element?

Recap

Use style.setProperty() to update CSS custom properties from JavaScript. Changes instantly propagate to all consuming elements. This pattern powers dynamic themes, animated progress bars, cursor effects, and scroll-driven animations — all without touching class lists or inline style strings for multiple properties.

Frequently asked questions

Is the “Updating Variables with JavaScript” lesson free?

Yes — the full text of “Updating Variables with JavaScript” is free to read here on the web, and the CSS Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the CSS Academy course, upgrade to CoddyKit PRO.

What will I learn in “Updating Variables with JavaScript”?

Dynamically update CSS custom properties from JavaScript using style.setProperty(). You practise CSS Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start CSS Academy?

No prior experience is required. CSS Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Updating Variables with JavaScript” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this CSS Academy lesson?

Yes. Every CSS Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Declaring and Using Custom Properties
  2. Fallback Values and var()
  3. Scoping Variables to Components
  4. Updating Variables with JavaScript
← Back to CSS Academy