The problem you are seeing is that by the time the browser renders the element, you have already added the "transition" class. Adding an element doesn't cause it to be rendered until it needs to be. Once an element has been rendered with the "starting value" and also has the transition css property set (from the "initial" classes), you can then add the other class to trigger your animation. You need the browser to have rendered the initial state before you add the other class or there is nothing to animate "from" and it comes in at it's full transition value.
You might try reading a value from that element like width
which should force a repaint before you add the other class: http://codepen.io/anon/pen/hGrFe
If you were going to take anthony's approach, I would suggest using requestAnimationFrame
instead of setTimeout
as that is guaranteed to be after a repaint has happened (assuming browser support for raf).
To save some repeating yourself, you could write your own repaint
method on jQuery:
jQuery.fn.repaint = function() {
// getting calculated width forces repaint (hopefully?!)
this.width();
// return chain
return this;
};
// then later:
$('<div class="alert fade">This is a test</div>')
.appendTo($someElement)
.repaint()
.addClass('in');