Sorry all for so many updates in this question and I'm glad for everyone trying to help me. I think below there is a more clear way to understand this problem:
CSS transitions will not apply if you set the display property of an element to block immediately before changing the property with the transition attached. Consider the following code:
CSS:
#creative {
display: none;
opacity: 0;
transition: opacity 0.5s;
}
HTML:
<div id="creative">
<span>Sample text</span>
</div>
Javascript:
var dom = {};
dom.creative = document.getElementById('creative');
dom.creative.style.display = 'block';
dom.creative.style.opacity = 1;
The element will properly show, but without any transition. A workaround for this problem is to force a repaint by accessing one of the visual properties of the element:
dom.creative.style.display = 'block';
var a = dom.creative.offsetHeight; /* <-- forces repaint */
dom.creative.style.opacity = 1;
is there a good way around this? and by good i mean not adding a extra line of javascript code everytime i need to change the display property and a property with a transition attached.
There are no transitions defined for absolute properties, like display. How do you interpolate between
none
andblock
? You can't. But you can create some post-functions that will run after the animation is done.Using setTimeout
You can use
setTimeout
and execute some code after the animation is over:Using animation events
As @trustk has pointed out, you can also (and preferably) use DOM events:
Based on the code you present in your question I'm going on a completely different way here, and use
animation
instead, which will make the whole repaint issue go awayUpdated with a script the set the div to
display: block
If
display: none
is not needed, one can usetransition
and simply toggle a class like thisFor
transition
, besides theoffsetHeight
and thesetTimeout
solution, there is a 3:rd, having the same visual effect as toggle display block/none, setting the height/width to 0.You can show / hide element without javascript using css transition only.
If you just add a timeout to the opacity call it should work! The duration can be almost nothing, as long as the display and opacity properties don't get called at the same time.
You can also use a jQuery fadein, if jQuery is an option. Then you can leave out the opacity altogether and just call it like...