Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect changes of CSSStyleDeclaration object in JS

Is there any way to get notified when a CSSStyleDeclaration object gets changed just like DOM changes which can be tracked using events like DomAttrModified?

So if there for example was some JS code like

document.styleSheets[0].rules[0].style.backgroundImage = "url(myimage.png)";

is there any way to get notified about that change in a JS handler without changing the code snippet above at all?

Thanks in advance!

like image 629
muffel Avatar asked May 23 '13 08:05

muffel


1 Answers

I don't think there is anything natively available for this.

Depending on your use case, you could easily build a wrapper, so that your code uses the wrapper and notifies the listeners that something changed.

Something quite basic like this:

function Wrapper() {
    var listeners = []

    return {
        addListener: function(fn) {
            listeners.push(fn)
        },
        removeListener: function(fn) {
            listeners.splice(listeners.indexOf(fn), 1) // indexOf needs shim in IE<9
        },
        set: function(prop, val) {
            prop = val
            // forEach needs shim in IE<9, or you could use a plain "for" loop
            listeners.forEach(call)

            function call(fn) {
                fn(prop, val)
            })
        }
    }
}

Which you could use like this:

var wrapper = Wrapper()
wrapper.addListener(function(prop, val) {
    // When you'll change a prop, it'll get there and you'll see
    // which property is changed to which value
})

// This sets the property and notifies all the listeners
wrapper.set(document.styleSheets[0].rules[0].style.backgroundImage, "url(myimage.png)")
like image 160
Florian Margaine Avatar answered Nov 15 '22 16:11

Florian Margaine