3

Can I use a MutationObserver to listen for changes on computed styles? I have a div which width is 100% and I'd like to know when its computed width changes, but so far no success. The MutationObserver works if I change the style pragmatically:

document.getElementById("myDiv").style.width = "200px"

But it doesn't work if the interface is resized by a window resize or if a parent div resizes.

Any solution that doesn't involve timeouts?

UPDATE: I'm particularly interested in a solution that also wouldn't involve listening to window resize event, because sometimes the interface changes without the window resizing. For instance, a div that has a percentage as width and a parent node size changes.

lbrandao
  • 4,144
  • 4
  • 35
  • 43

1 Answers1

7

Support for observing style changes is in discussion. For now you could leverage transitions. The idea is to add a css transition for the width (or whatever) to the element. The transition should have a duration of almost zero, so you won't notice it.

After a transition has finished a transitionend event is fired. Add a listener for that event. Now whenever the width changes, the transition will start, immediately finish and the event will fire. Which means your listener will be called.

#myDiv {
  ...
  transition: width 0.01s;
}

$("#myDiv").on("transitionend", function () { ... } );

Supported by IE10+

a better oliver
  • 26,330
  • 2
  • 58
  • 66
  • 1
    That's interesting but it still doesn't work for indirect changes. If a div has a percentage as width and a parent node size changes, no transition will happen. – lbrandao Sep 25 '15 at 02:30
  • @fromvega That's true :( On the other hand, such change is always preceded by **some** event, be it window resize or a direct style change of a parent element. The only situation difficult to handle with events are growing elements (e.g. by adding content). But you always have a solution that doesn't involve timeouts. Just not a direct one. If you want to do some kind of layout change based on the size, most of the time that can be done using css only, maybe with some media queries. Ideally a change of size shouldn't concern you at all. – a better oliver Sep 25 '15 at 07:57