loading...

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

adam_cyclones profile image Adam Crockett ・1 min read

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.

Discussion

pic
Editor guide
 

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.

 

This would do the trick πŸ₯°

 

Why should you do this?

 

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?

 
 

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! πŸ‘

 

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.

 

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

 

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

 

After reading the comments above?