3

Is there an event I can listen for in JavaScript that tells me the computed style for a particular DOM element has changed?

If not, what is the least blocking way to get the computed style of a DOM element using JavaScript?

  • Seems unusually to need to trigger code on a style change. Can't you hook into the code that's actually changing the style? I don't know of any event that fires on a style change. –  Jul 03 '15 at 00:10
  • I have a bunch of SVG's that visually model mathematical data. When the window resizes, I need to get computed styles of each visualization's parent element, then use math to calculate properties of the element's children using computed styles and data from the model the math is visualizing. So, the trigger is a resize event; the styles of the child elements depend on their parent's computed style and other input data. –  Jul 03 '15 at 00:14
  • If the trigger is a resize, then yes you can run code when the window resizes and then get the computed styles you need. Your question makes it sound like you want a style-change trigger. –  Jul 03 '15 at 01:21
  • I do. There are so many things that trigger style computations, it would be nice to have a single event to listen for. –  Jul 03 '15 at 03:19
  • For **get**ing the **computed** **style**, it sure would be nice if there was a method called something like, oh maybe, `getComputedStyle`. By the way, what do you mean by "blocking"? All code blocks while it's running. –  Jul 03 '15 at 03:31

1 Answers1

0

There is no event listener for on change of computed style of a DOM element.

You can write one yourself if you are fancy, watching the value of getComputedStyle through setInterval, but it could be expensive and unwieldy depending on implementation.

If you are only worried about style changes on resize you should use the window.onresize (below), or possibly the JQuery resize event handler.

window.onresize = function(event) {
    ...
};

There is a very good read here about in depth cross browser solution for referencing CSS3 properties, however the following is a simple solution for various popular browsers via this answer.

It's not jQuery but, in Firefox, Opera and Safari you can use window.getComputedStyle(element) to get the computed styles for an element and in IE<=8 you can use element.currentStyle. The returned objects are different in each case, and I'm not sure how well either work with elements and styles created using Javascript, but perhaps they'll be useful.

In Safari you can do the following which is kind of neat:

document.getElementById('b').style.cssText = window.getComputedStyle(document.getElementById('a')).cssText;
Community
  • 1
  • 1