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.
You got to be kidding, this is like JS/CSS wedding.
Relevant, use React to stagger animations with a CSS variable:
https://twitter.com/DavidKPiano/status/1009499115720495114
I’d add
* { cursor: none; }
for demo purpose.Is it more powerful than setting directly the
top
andleft
style of an element ?I see at least two advantages. One is the CSS readability: If you want to pin an element to the position of your cursor,
left: var(--mouse-x)
just makes total sense to me. And if there are more than one element reacting to the movement of your mouse, you don’t have to update them one by one in your JS – you simply update the CSS variable once. Mixed with a few other CSS techniques this pretty much opens up for a whole lot of new opportunities. I just played around with this to make some custom scrollbars and I’m sure there are plenty of other use cases! :-)Yeas, I already use these powers evry day actually ! So great… until your client asks for IE compatibility. Anyway, I just decided to drop all IE projects, because I really like CSS variables really much !
My question was more about performance : is it more performant to set a CSS variable than setting the
top
andleft
styles directly ?