0

I'm creating a div using JavaScript and inserting it into a page. I'm doing this by changing the parent div's transform: translateY to shift it up by the div's height, inserting the div, then sliding it back down.

Here's the basic code:

attachTo.style.transform = 'translateY(-' + divHeight + 'px)';
attachTo.insertBefore(div, attachTo.firstElementChild);
attachTo.style.transition = 'transform 2s';
attachTo.style.transform = 'translateY(0)';

With that code the transform time is ignored and the added div pops in as normal. If I change it to something like this, however:

attachTo.style.transform = 'translateY(-' + divHeight + 'px)';
attachTo.insertBefore(div, attachTo.firstElementChild);

// Either of these can be used, as can any statement or expression that queries an element's CSS styles. 
console.log(document.body.clientHeight);
var foo = pageWrap.offsetParent;

attachTo.style.transition = 'transform 2s';
attachTo.style.transform = 'translateY(0)';

The div will animate properly. Less surprisingly to me, I can also wrap the final transition and transform changes in a zero-length timeout.

The behaviour's the same in Firefox and Chromium.

My question is why this happens, and why the code isn't executed synchronously? I'm thinking it's related to the browser's execution queue, as covered in this question about zero-length timeouts, but not only would I like to know for certain that's the case, I'd also like an explanation on why using a DOM element's style property achieves the same effect (my guess is it creates a slight pause in execution).

Community
  • 1
  • 1
chrBrd
  • 603
  • 5
  • 23

1 Answers1

1

When javascript runs a series of commands, the browser does not redraw the elements until it is done, or if one tell it to, and since the last command resets everything, nothing happens.

This is also the case with many other programming languages.

So one either have to put it in a function, in this case using a setTimeout, or call for example window.scrollHeight in between, to make the browser redraw.

Why a property is used is because javascript does not have a method, like for example Application.DoEvents(); in Dot.Net.

Src: What forces layout / reflow in a browser

Asons
  • 84,923
  • 12
  • 110
  • 165
  • I knew how to fix it, what I didn't know was why it was happening - you've answered that perfectly, so thanks. That link is very useful too. – chrBrd Jan 29 '17 at 20:25