Problem
If adding css transition on a just-appended element, the transition will not work as expected. Take the below code as example.
// css
.fade-in {
opacity: 0;
}
.fade-in.show {
opacity: 1;
transition: opacity 1s linear;
}
var el = document.createElement('p');
el.classList.add('fade-in');
document.body.appendChild(el);
el.classList.add('show');
This is because browsers optimizes the final repaint for all changes commited in our single-thread javascript. As we create an element and add a class, browser does not paint anything as the code doesn’t change the render tree. It update the dom tree when we append the element to document, and thus change the render tree. This is the first time the render tree updates. When we add a new class to the element, it causes the style rule tree changes and the render tree changes again. There are twice upates in the render tree, but browser will batch the first one and merge them into a final update. In conclusion, the browser calculate the final styles as you set and update in a sequatial javascript, ignoring the initial state and causing the final repaint. Therefore, the transition for a appended element doesn’t animate as there’s only one final repaint for the final styled element.
Solution
To make the transition work, we have to make the browser ‘paint’ twice (of course it will paint multiple times if transition is fired). The easiest way is to put the action the needs to be executed after the repaint in a setTimeout
. Take the beginning code as example, we modify it to:
// css
.fade-in {
opacity: 0;
}
.fade-in.show {
opacity: 1;
transition: opacity 1s linear;
}
var el = document.createElement('p');
el.classList.add('fade-in');
document.body.appendChild(el);
setTimeout(function() {
el.classList.add('show');
}, 10);
Then the transition fire and animate. Here we add 20ms to the action as browser repaint a frame needs 6ms if it the fps is 60. setTimeout
cause asynchorous result which you might modify it with promise
if you need other callback actions after the repaint.
The second way is to cause the repaint in javascript. If we request for the demension or painted styles of the element, the browser have to repaint it and calculate it.
// css
.fade-in {
opacity: 0;
}
.fade-in.show {
opacity: 1;
transition: opacity 1s linear;
}
var el = document.createElement('p');
el.classList.add('fade-in');
document.body.appendChild(el);
// cause the repaint by calculating the element's dimension
var width = el.offsetWidth;
el.classList.add('show');
It works for most of occasions, but also bring performance issues as it causes more repaints. So keep in mind that don’t use it inside actions that cause frequent repaint.