DEV Community

Adam Crockett 🌀
Adam Crockett 🌀

Posted on

Can CSS variables be watched, (need a smart cookie)

The best thing since sliced bread and absolutely the most revolutionary thing I have seen in my time as Dev, is CSS variables, it's shocking because it's something that should have been there from day one.

Let's get to the question, given I can get and set CSS variables in JavaScript 🥰, can I also watch for changes to the CSS values on the fly?

Other than polling, are there any ways to observe a live CSS variable change?

onCustomPropertyChange

I think the answer is no.

Top comments (10)

Collapse
 
alvaromontoro profile image
Alvaro Montoro

Maybe you could use a MutationObserver?

But it would depend highly on what you are doing. Watching the value is not trivial and depends on many factors. Take into account that CSS variables can change their value in many different ways and within many different scopes.

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀

This would do the trick 🥰

Collapse
 
pfacklam profile image
Paul Facklam

Why should you do this?

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀 • Edited

Based on the reaction of this post

Jess has become a language, you can see in my series jesslang, and part of the compiled code would ideally watch for changes so that CSS can become reactive in a narrow scope.

There would be a fair bit to read in my posts so forget the why, how?

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀
Collapse
 
joshuajarman profile image
Joshua Jarman • Edited

Look into using MutationObserver with CSSOM: codepen.io/tainan/pen/vvzbwv

Also worth checking out cssobj/cssobj and zeit/styled-jsx to see how a few other projects handle reactive css aspects with javascript.

also worth looking into what can be done with houdini. 🎩🐇

Reactive css is tricky, css variables are tricky, when they are evaluated, how and where they are set, in what ways and when they are static or dynamic, the cascade of full/partial inheritance/override both to and from, late unsetting, invalid value handling and falling back, the interplay of different units, etc. there are some helpful tricks like calc() wraps etc. this is all new exciting ground for css! 🎉

best of luck, it is exciting seeing these concepts being explored and pushed forward! 👍

Collapse
 
wolfiton profile image
wolfiton • Edited

How about vuejs.org/v2/guide/computed.html#C...?

Vue is reactive and will also help you extend any features you might need in the future and has watchers for events.

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀

Indeed the reactive idea is what I am looking for and Vue is the inspiration for what I am talking about, but this is a bit high level, I'm looking for probably MutationObserver

Collapse
 
outthislife profile image
Talasan Nicholson

I can't think of a single use case. Do you have one?

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀

After reading the comments above?