Home > Designing, Others > Updating a CSS Variable with JavaScript

Updating a CSS Variable with JavaScript

September 12th, 2018 Leave a comment Go to comments

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.

The post Updating a CSS Variable with JavaScript appeared first on CSS-Tricks.

Categories: Designing, Others Tags:
  1. No comments yet.
  1. No trackbacks yet.
You must be logged in to post a comment.