Updating a CSS Variable with JavaScript
Get affordable and hassle-free WordPress hosting plans with Cloudways —start your free trial today.
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 PenSet CSS Variable with JavaScript by Chris Coyier (@chriscoyier) onCodePen.