Friday, November 22

Updating a CSS Variable with JavaScript

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.

Source: CSS-tricks.com

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x