开发者

jquery applies the .addClass() before the fadeOut() applied

I am doing something like this:

case: when i click on add link it should remove the class style on Div and Fadeout and then it should add a class and then fadein. But the problem is it removes the class, then adds class then performs fadeout and fadeIn. Why it is adding the class before fadeout?

he开发者_JS百科re is my code

$(function(){
    $('#noti1').click(function() {
        $('#blue').removeClass( "ui-state-highlight").fadeOut(1000, mossawir);

        function mossawir() {
            setTimeout(function() {
                $( "#effect" ).addClass( "newClass" );
            }, 1500);
        }

        $('#blue').addClass("ui-state-error").fadeIn('slow');
     });
});

I even tried a more simple way:

$(function() {
    $('#noti1').click(function() {
        $('#blue').removeClass( "ui-state-highlight").fadeOut('slow');
        $('#blue').addClass("ui-state-error").fadeIn('slow');
    });
});


That's because animation methods like fadeOut() and fadeIn() are asynchronous: they return immediately and perform their work later.

Since asynchronous methods return before they complete, they usually take a callback function argument that gets called when they do complete. In your case, you only need to run the fadeIn animation when the fadeOut effect completes, i.e. in its callback:

$("#noti1").click(function() {
    $("#blue").removeClass("ui-state-highlight").fadeOut("slow", function() {
        $(this).addClass("ui-state-error").fadeIn("slow");
    });
});


It's adding the class before you fade out because that's exactly what you told it to do.

jQuery's normal methods aren't processed as part of the animation queue, they're executed immediately.

You could try:

$('#blue')
   .removeClass('ui-state-highlight')
   .fadeOut(1000, mossawir)
   .queue(function() {
       $(this).addClass('ui-state-error')
       $(this).dequeue();
   })
   .fadeIn('slow');

to insert the class change as part of the animation queue.

NB: this method preserves your existing completion callback (mossawir) to add the newClass effect once the .fadeOut had completed. The other answers don't allow for that (yet).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜