0

I'm looking for a way to listening with MutationObserver for a changes in CSS custom vars, actually i'm using the CSS custom vars defined into main index.html file to trigger the different themes of the Web contents. What i want it's a clean MutationObserver solution i can use in all / parent /child CustomElements to listening for a changes of a CSS custom var on that DOM element rules from the changes of the CSS custom var in the index.html main file.

Actually i cannot listening for a changes propagate down the three from a CSS Custom var. Eg. the code i'm using in the CustomElement to listening for the style changes:

#initObserver () {
    const brand = this.renderRoot.querySelector('#brand')

    const observer = new MutationObserver(
        this.#customStylesMutation
    )
    observer.observe(brand, {
        attributes: true,
        attributeFilter : ['style']
    })
}
cicciosgamino
  • 871
  • 3
  • 10
  • 29
  • What is your actual goal? Listening to a style change and executing business logic sounds awkward to me. – Christian Jan 12 '22 at 10:25
  • Basically bacause i've childs nested elements that need to change when a CSS custom vars eg. in the index.html the --text1: var(--text1-light); custom property changes based on the light / dark mode trigger ... i'd like have deep in the CustomElements childs tree an element that can listen for the changes in the CSS custom var --text1 – cicciosgamino Jan 12 '22 at 15:27
  • why don't you just use the media query `@media (prefers-color-scheme: dark)`? And what does the customelement do, when the custom var changes? Maybe your goal can be reached in a different way. – Christian Jan 12 '22 at 21:15
  • Of course the goal can be reached in different way ...but i need to establish a chain down the tree with the attribute go down and events go up! But if i choose to change the value of the CSS custom var in the index.html file it's seems to me good feature understand in the element when that CSS custom var value changes ! – cicciosgamino Jan 13 '22 at 09:55
  • I don't know if it is feasible at all, despite not very useful, imho. Changing a var in the root, does recalculate the whole cascade. vars are scoped and conditional. Maybe 'u'r lucky observing `element.style.getPropertyValue("--var");` or `getComputedStyle(element).getPropertyValue("--var"); `. You could change properties of the element, observe that and based on that set the var in the style of an element. But CSS is not made for information transport. But be aware of the performance: see desc. in https://www.npmjs.com/package/computed-style-observer – Christian Jan 13 '22 at 14:56

0 Answers0