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