Question

I am trying to achieve the following. I want a fade animation between two different divs. The animations are successful. Only when one div is fading out, the content of the div fading in jumps down. I think its a animation timing question.

 $('#btn').click(function () {
     $('#services').fadeOut('slow', function(){
         $('#prices').fadeIn('slow'); 
         });

    if ($('#services').is(':visible')) {
        $('#services').fadeOut('slow');
        $('#prices').fadeIn('slow')
        $('#btn').html('Services');
    } else {
        $('#btn').html('Prices');
        $('#prices').fadeOut('slow');
        $('#services').fadeIn('slow')
    }
});

I can't find any solutions on the web. Here is my http://jsfiddle.net/z7E3A/4/

Pas de solution correcte

Autres conseils

You need to put the second fading action inside the complete function of the first fading action. Also it would be more efficient if you cache the jquery elements since we are reusing it multiple times

http://jsfiddle.net/z7E3A/7/

var btn = $('#btn');
var service = $('#services');
var price = $('#prices');

btn.click(function () {
     service.fadeOut('slow', function(){
         price.fadeIn('slow'); 
     });

    if (service.is(':visible')) {
        service.fadeOut('slow', function(){
            price.fadeIn('slow');
            btn.html('Services');
        });

    } else {
        price.fadeOut('slow', function() {
            service.fadeIn('slow');
            btn.html('Prices');
        });

    }
});

Simpelest solution is to run the fadeIn after the fadeOut like so:

 $('#btn').click(function () {
     $('#services').fadeOut('slow', function(){
         $('#prices').fadeIn('slow'); 
         });

    if ($('#services').is(':visible')) {
        $('#services').fadeOut('slow', function(){
            $('#prices').fadeIn('slow');
        });
        $('#btn').html('Services');
    } else {
        $('#btn').html('Prices');
        $('#prices').fadeOut('slow', function(){
            $('#services').fadeIn('slow');
        });
    }
});

See fiddle: http://jsfiddle.net/z7E3A/5/

An alternative is to make one of the divs positioned absolute through CSS:

#services {
    width: 100%;
    height: auto;
    background: yellow;
    position: absolute;
    top: 0;
    left: 0;
}

This would result in a smoother animation, but won't work as easy if the div's differ in height.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top