Updating a CSS Variable with JavaScript

Avatar of Chris Coyier
Chris Coyier on

Here’s a CSS variable (formally called a “CSS custom property“):

:root {
  --mouse-x: 0px;
  --mouse-y: 0px;
}

Perhaps you use them to set a position:

.mover {
  left: var(--mouse-x);
  top: var(--mouse-y);
}

To update those values from JavaScript, you’d:

let root = document.documentElement;

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

That’s all.

See the Pen Set CSS Variable with JavaScript by Chris Coyier (@chriscoyier) on CodePen.