Reputation: 20011
I'm trying to add an element to the DOM and then add a new class to trigger a transition animation.
// -- 1 -- Circle Already is in the DOM
// <div class="circle circle1 hwaccel"></div>
$('.circle1').addClass("dropped"); // Works!
// -- 2 -- Circle is added to the DOM with jQuery
var $c = $('<div class="circle circle2 hwaccel"></div>').appendTo( $('body') );
$c.addClass("dropped");
// Doesn't animate. Also tried $c.toggleClass("dropped");
// -- 3 -- Circle is added to the DOM with vanilla JS
var circleClass = "circle circle3 hwaccel";
var circleElt = document.createElement("div");
circleElt.setAttribute("class", circleClass);
document.body.appendChild( circleElt );
circleElt.setAttribute("class", circleClass + " dropped");
// Doesn't animate. :(
What am I doing wrong? fiddle is here: http://jsfiddle.net/luken/DsLhJ/
Upvotes: 3
Views: 1341
Reputation: 40671
Someone will have to speak up with the proper terminology to explain why this is necessary, but I can explain what you need to do.
You can't add and apply the style in the same action. The browser needs a 'start' class and an 'end class' applied separately. The easiest fix is to wrap the addition of the class inside a setTimeout.
So change this:
var $c = $('<div class="circle circle2 hwaccel"></div>').appendTo( $('body') );
$c.addClass("dropped");
To this:
var $c = $('<div class="circle circle2 hwaccel"></div>').appendTo( $('body') );
setTimeout(function(){
$c.addClass("dropped");}
,0)
The setTimeout adds that 'disconnect' between the action of adding it to the dom, and then changing the class (again, someone with more JS knowledge will have to chime in with the proper technical explanation as to why that works).
Upvotes: 1