Below is a contrived example where I append two elements to a page. The first box has a decorative class given to it immediately. The second box has the class given to it after a setTimeout of 1ms has elapsed.
In my example, I appear to always see the second box transition. However, in my larger application, I infrequently see an element rendered without its transition. The element transitions in OK when I attempt to reproduce the issue, but then, a while later after many successful transitions, I see it once again appear without its transition.
I'm wondering if the setTimeout fix is guaranteed to work. Is my problem a race condition, or is my problem elsewhere?
$('#runExample').click(function() {
$('.example').remove();
var example = $('<div>', {
'class': 'example'
});
$('body').append(example);
example.addClass('is-colorful');
var example2 = $('<div>', {
'class': 'example'
});
$('body').append(example2);
setTimeout(function() {
example2.addClass('is-colorful');
}, 1);
});
.example {
width: 200px;
height: 200px;
background-color: red;
transition: background-color 2s;
display: inline-block;
margin: 0 10px;
}
.example.is-colorful {
background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='runExample'>
Run Example
</button>