Ben Kulbertis
Ben Kulbertis

Reputation: 1713

jQuery fadeOut() skips after CSS fade in

I'm having a bit of a frustrating problem regarding fading out an element using jQuery after it has been faded in with CSS. I set up a CSS animation to fade in an element when the page loads using the following (I've also got the relevant browser prefixes included too, I'm using Stylus):

@keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
.elem {
    opacity: 0;
    animation: fadein 500ms ease-in 1ms forwards;
}

My issue is that when an event handler is activated that runs the following, the fadeOut does not fade but instead skips straight to nothing:

    $('.elem').fadeOut(400, function(){
        $('.elem').fadeIn(400);
    });

I've been able to replicate the issue in this JSFiddle. Can anyone help me out? :) Thanks a lot!

Upvotes: 0

Views: 302

Answers (3)

faerin
faerin

Reputation: 1925

I know you asked for FadeIn and FadeOut... here's your code with animate and opacity instead.

$('#go').click(function(){
    $('.elem').css('animation','none').animate({
        'opacity' : 0
        },function(){
            $('.elem').animate({
                'opacity' : 1
                });
        });
    });

Upvotes: 1

christian314159
christian314159

Reputation: 639

It seems that the css-animation has higher precedence than the inline style that jQuery applies to the element when fadeOut is used. This means the animation's opacity : 1; overrides any opacity setting jQuery applies, up until jQuery sets the element to display:none;

You can do this to get around:

$('#go').click(function(){

   $('.elem').css('animation','none').fadeOut(400, function(){
      $('.elem').fadeIn(400);
    });

});

Upvotes: 0

scrowler
scrowler

Reputation: 24406

I would say it's conflicting with the CSS you're using. jQuery is probably using other opacity related properties than what your CSS is. An all jQuery solution might be this:

CSS

.elem {
    display: none;
}

jQuery

$('.elem').fadeIn(1000); // on page load, fade in with jQuery

$('#go').click(function(){
    $('.elem').fadeOut(400, function(){
        $('.elem').fadeIn(400);
    });
});

Related: Conflict between CSS transition and jQuery fade

Upvotes: 1

Related Questions