2

Suppose some piece of code changed a size of an element and called my callback:

$element.css("width", 500);
elementsWidthChanged();

For the demonstration purposes suppose there is no way the new size can be passed to the callback. So inside the callback I'm trying to get new size:

function elementsWidthChanged() {
   var width = $element.outerWidth();
}

Do I always get the new dimensions? Or do I need to wait for the repaint to occur?

user2864740
  • 60,010
  • 15
  • 145
  • 220
Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488
  • I think it will depend on various factors. One of them being the css animation. If there is an animation on width or height then depending upon the time frame of the animation you' may or may not get the new dimensions. Similar to this, there will be other factors too. – K K Aug 01 '15 at 08:26
  • @KK, thanks, can you list other factors too? – Max Koretskyi Aug 01 '15 at 08:32
  • 1
    I asked [a similar question awhile ago](http://stackoverflow.com/questions/26813480/when-is-element-getboundingclientrect-guaranteed-to-be-updated-accurate) .. but no takers. My experience indicates 'the size update is immediate' (not tested under CSS animations) but I cannot find any definitive answer. – user2864740 Aug 01 '15 at 08:33
  • 2
    Some useful reading in http://stackoverflow.com/questions/510213/when-does-reflow-happen-in-a-dom-environment?rq=1 – user2864740 Aug 01 '15 at 08:40
  • The repaint may not be immediate, but the repaint takes place if something (let say JavaScript code) tries to **read** a property needing a repaint. – Mat Aug 01 '15 at 08:43
  • @user2864740, thanks, I think the sizes are defined at reflow stage and are not affected by repaint stage. Now the question is whether reflow takes place immediately or waits until a callstack is empty? – Max Koretskyi Aug 01 '15 at 08:55

1 Answers1

5

The answer is that a reflow happens when you query the DOM for the new width. So yes, $element.outerWidth(); will return the new value. I found this article helps explain how the browsers handle reflows/repaints. But a brief summary:

The browser has a queue of DOM changes. When you set $element.css("width", 500); the change is added to the queue. Since DOM changes are expensive, the browser doesn't do them immediately. However, when you query the DOM for the new width it flushes the queue, updating the DOM, doing a reflow, and returning the new value. You can see this by doing a javascript profile. You'll notice that most of the time is spent in the .outerWidth() call doing the reflow, not the .css call.

JosiahDaniels
  • 2,411
  • 20
  • 37