CSS Transition Not Firing

Kong picture Kong · Aug 15, 2011 · Viewed 17.8k times · Source

I'm creating a DOM element (a div), adding it to the DOM, then changing its width all in one quick hit in javascript. This in theory should trigger a CSS3 transition, but the result is straight from A to B, without the transition in between.

If I make the width change through a separate test click event everything works as expected.

Here's my JS and CSS:

JS (jQuery):

var div = $('<div />').addClass('trans').css('width', '20px');
$('#container').append(div);
div.css('width', '200px');

CSS (just mozilla for the minute):

.trans {
    -moz-transition-property: all;
    -moz-transition-duration: 5s;
    height: 20px;
    background-color: cyan;
}

Am I messing up here, or is the "all in one quick hit" not the way things should be done?

All help is really appreciated.

Answer

Torin Finnemann picture Torin Finnemann · Nov 11, 2013

A cleaner approach that does not rely on setTimeout, is to read the css property in question before setting it:

var div = $('<div />').addClass('trans');
$('#container').append(div);
div.css('width');//add this line
div.css('width', '200px');

Working here:

http://jsfiddle.net/FYPpt/144/

As explained in the comments below by Lucero, doing it this way is necessary to force the browser to calculate an actual value rather than "auto", "inherit" or similar. Without an actual value, the browser will not know the new value to be a change from the previous.