jquerytoggleclassfadeto

Why does jQuery.fadeTo not animate if toggleClass is called in the callback?


I have a modal box that starts with a class "hidden" which makes the modal display: none; (To keep the invisible modal from capturing mouse clicks)

To fade in the modal I do

jQuery('#modalID').toggleClass('hidden'); <-- Makes the modal display: block; by removing the "hidden" class
jQuery('#modalID').fadeTo(.3, 1.0);

Which works perfectly. The problem is when I try to toggle the "hidden" class back on after a fade out (to make it display:none: again). When I try to toggle the "hidden" class in the fadeTo callback the modal just disappears instantly. Here's my code

jQuery('#modalID').fadeTo(.3, 0, function(){
    jQuery('#modalID').toggleClass('hidden'); <-- *should* make the modal display:none AFTER fading it out....
});

I've tried to explicitly add the class in the fadeTo callback

jQuery('#modalID').fadeTo(.3, 0, function(){
    jQuery('#modalID').addClass('hidden');
});

and even tried ignoring the callback altogether and just putting the commands back to back...

jQuery('#overlayID').fadeTo(.3, 0); jQuery('#overlayID').toggleClass('hidden');

How can I fade the modal out, and then add the "hidden" class back to the modal afterwords?


Solution

  • The issue is due to your duration parameter. It's given in miliseconds, so your setting of .3 means 0.0003 seconds. Hence the fade appears instantaneous, and the callback immediately triggered.

    To fix this, presumably, you want the animation to last 0.3 seconds, so the value should be 300. Try this:

    $('#modalID').fadeTo(300, 0, function(){
        $(this).toggleClass('hidden');
    });
    

    Also note that you could just use fadeOut() and avoid the use of the second parameter for opacity.