What I want to do:
Add a new element to my DOM and animate its opacity with css3.
My solution
A div ".bar.fade" is added via JavaScript and then a class "in" will instantly added.
Problems with my solution
Without using the setTimout() function, the div will instantly be drawn visible (without css transition). Why does this happen and how to prevent it? I assume, using setTimeout() isn't the best practice, is it?
SCSS
.bar
{
position: absolute;
bottom: 0;
top: 0;
width: 100%;
background-color: red;
z-index: -1;
opacity: 0;
visibility: hidden;
&.fade
{
@include transition(
visibility .75s ease-in-out,
opacity .75s ease-in-out
);
}
&.in
{
opacity: 1;
visibility: visible;
}
}
JS (Zepto)
$('.foo').on('click', function() {
$('body').append('<div class="bar fade"></div>');
$('.bar').addClass('in');
});
$('.fooDelay').on('click', function() {
$('body').append('<div class="bar fade"></div>');
setTimeout(function(){
$('body > .bar').addClass('in');
}, 50);
});
$('.fooRemove').on('click', function(){
$('body').find('.bar').remove();
})
I've made a codepen for better testing: http://codepen.io/dschu/pen/wBVmLp