So, I've been playing around with CSS Variables lately. And once the initial mind-blending effects settled down about the how they work, I started thinking beyond managing theme colors and preset property values.

And after learning of this dark magic, I've amped up my ponderings of what's possible:

  // from a session at the 2016 CSS Dev Conference by David Khourshid
document.addEventListener('mousemove', (e) => {
  document.documentElement.style.setProperty('--mouse-x', e.clientX)
}

"Well, how far can we take this new-fangled funness?" I keep asking myself.

I see your theme, and I'll raise you some data feedback.

I started working on a CodePen toy that needs constantly updated mouse coordinates to provide some special feedback to User. Sure, this is no big deal to make The JavaScripts do this, but now I'm a var(--princess) and I don't want to use jQuery (I just vurp'd a little), or Angular's ngWhatever patterns (gross!), or vanilla JavaScript (meh...) — stuffing attributes on things and messing with the DOM (ew!). I want CSS to do it!

Side Note

I realize the document.documentElement.style.setProperty darkness is actually manipulating the DOM with an inline style attribute at the <html> tag level, but something about that just feels okay to ignore. ;)

This was my first attempt:

Oh no!, I thought, CSS variables don't work in pseudo-element content properties! How can that be?! What ever will I do?

After a poking around a bit on Stack Overflow, I finally asked my first question ever! See the pen below using the hack / solution provided Darryl Yeo.

CSS Counters, Yo! I mean, Yeo!

Brilliant. CSS can't (yet) do type conversions, but reallocating the variables to counter trackers... nice!

While the transform on the div was working great at consuming the raw numbers that JavaScript was feeding to the vars, the content: property was like, "Up yours! I can't be bothered with whatever this is you're trying to give me... Go away."

At first, the suggestion was to force the stringiness in JavaScript Land before the hand-off to the CSS variable:

  document.documentElement.style.setProperty('--mouse-x', "'" + e.clientX + "'")

And that ↑ worked for displaying the data updates in the pseudo-element, but then the transform borked out 'cause it didn't like the numbers as strings.

Hugo Giraudel wrote about casting types in SASS, but then he also chastises anyone needing to do that:

Something so simple as changing a stringified number into an integer is actually quite difficult to do in Sass, yet sometimes you might find yourself in the need of doing that (which means there is probably something wrong somewhere in your code by the way).

I don't know if what I'm doing here is wrong but it sure is fun! And that, my friends, allows me to accept my cubicle situation at work (most of the time).

CSS Counters... I love this stuff!


3,593 2 33