Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery fadeOut/fadeIn not working as expected?

I'm trying to show one fieldset at a time, based on the user's selection. The theory is that, all fieldsets should hide first, then the selected fieldset should be shown. I'm using jQuery's fadeOut and 'fadeIn` functions.

You can see a fiddle of this here.

But it doesn't work just fine. What's wrong? When you change the ownership type, first two fieldsets are shown, then they dim and fade out, and then the intended fieldset appears. However, the desired behavior is that, on change of the ownership type, the currently visible fieldset simply fade out, and then the intended fieldset fade in.

like image 239
Saeed Neamati Avatar asked Oct 04 '11 07:10

Saeed Neamati


3 Answers

You can also use a 'promise' http://api.jquery.com/jQuery.when/ to be sure that fadein happens after when fieldset has faded out.

$(function() {
    var ownershipType = $('#ownershipType').first();
    var fieldsets = $('fieldset');
    ownershipType.change(function() {
        var promise = fieldsets.fadeOut(2000);
        $.when(promise).then( function () {$('fieldset[data-ownership-type=' + ownershipType.val() + ']').fadeIn('fast');
        });
    });
});

http://jsfiddle.net/DtaHQ/26/

like image 53
Vertigo Avatar answered Nov 08 '22 22:11

Vertigo


The problem is that you already have hidden fieldset and for these elements animation of the fadeOut fires immediately, because of it's already hidden.

Try to change to this:

$(function() {
    var ownershipType = $('#ownershipType').first();
    ownershipType.change(function() {
        $('fieldset:visible').fadeOut(2000, function() {
            $('fieldset[data-ownership-type=' + ownershipType.val() + ']').fadeIn('fast');
        });
    });
});

Code: http://jsfiddle.net/DtaHQ/20/

like image 20
Samich Avatar answered Nov 09 '22 00:11

Samich


Change your code to

$(function() {
    var ownershipType = $('#ownershipType').first();
    var fieldsets = $('fieldset');
    ownershipType.change(function() {
        $('fieldset:visible').fadeOut(2000, function() {
            $('fieldset[data-ownership-type=' + ownershipType.val() + ']').fadeIn('fast');
        });
    });
});

You only want to fade out the fieldset that is currently visible.

http://jsfiddle.net/DtaHQ/24/

like image 37
Ray Toal Avatar answered Nov 08 '22 22:11

Ray Toal