How to update CSS variables with JavaScript

September 21, 2019

by Yunus Shaikh

We have CSS variable as


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

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


To update above values using Javascript, You would need to do


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