Detect CSSStyleDeclaration object changes in JS

Is there a way to get notified when the CSSStyleDeclaration object changes in the same way as DOM changes that can be tracked with events like DomAttrModified?

So, if, for example, there was some JS code, for example

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

is there a way to get notified of this change in the JS handler without changing the code snippet above?

Thanks in advance!

+7
source share
1 answer

I do not think there is anything available for this.

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

Something very simple:

 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) }) } } } 

What you can use as follows:

 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)") 
+1
source

All Articles