Skip to content

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

github logo ・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?


I think the answer is no.

twitter logo DISCUSS (10)
markdown 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.


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:

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! 👍


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


How about

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

Classic DEV Post from Jul 20 '19

What Makes You a Great Programmer on The Team?

Majority of software developers are aspired to be not only a competent professional but also a great one.

Adam Crockett profile image
I work at ForgeRock as a Front End Engineer, I play with all sorts really. Lately WASM is my toy of interest.

The worldwide software forum.

Create Your Account