Wednesday 12 September 2018

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.

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.



from CSS-Tricks https://ift.tt/2MqEtg9
via IFTTT

No comments:

Post a Comment

Passkeys: What the Heck and Why?

These things called  passkeys  sure are making the rounds these days. They were a main attraction at  W3C TPAC 2022 , gained support in  Saf...