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!
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)")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With