I use JavaScript to dynamically add an element to the DOM. I want to use CSS3 transitions to βfadeβ an element as it is added.
For this, I use something like the following:
function add(el) { el.className += ' fader'; el.style.opacity = 0; document.getElementById('parent-element').appendChild(el);
And CSS:
.fader { -webkit-transition: opacity 0.5s; }
This does not work as expected - the element does not disappear. If I replace the line el.style.opacity = 1; on setTimeout(function () { el.style.opacity = 1; }, 5); as seen above, it works as expected.
I assume that the first case does not work, as there is some delay between adding an element and the corresponding CSS rules that apply to it. The 5 ms delay created by setTimeout in the second case gives enough time to apply these rules, so the attenuation occurs as expected.
Firstly, is this a correct assumption? Secondly, is there a better way to solve this problem? setTimout looks like a hack. Is it possible for some event that is fired after an element has used all its styles?
source share