Brandon Nadeau
Brandon Nadeau

Reputation: 3706

jQuery: How to wait until fadeTo(or any other effect) finishes before executing code

I'm making a news board that fades the news in and out. When the element fades out the content gets deleted, when it fades back in there is new content in its place. This works, just the timing is off. The new content that should only appear when the old content has faded away, appears as the element is fading. Is there a way to wait until this is done?

$(document).ready(function() {
    var counter = 0;
    var slides = ['<p>Track All of Your enemys Using The <span>Scout Tool!</span></p>',
                    '<p>Download powerups Using The <span>Pirate Tool!</span></p>',
                    '<p>Gather Badges To Attack others in <span>Raids!</span></p>',
                    '<p>Enjoy Orgainzing Your Profile <span>Join Now!</span></p>'];

    $('#slide-left').click(function() {
        $('#slide').fadeTo('fast', 0);
        $('#slide p').remove();

        if (counter > 0){counter --;}

        $('#slide').append(slides[counter]);
        $('#slide').fadeTo('fast', 1);
    });
    $('#slide-right').click(function() {
        $('#slide').fadeTo('fast', 0);
        $('#slide p').remove();

        if (counter < (slides.length-1)){counter ++;}

        $('#slide').append(slides[counter]);
        $('#slide').fadeTo('fast', 1);

    });

});

Upvotes: 0

Views: 729

Answers (3)

Nuno Sim&#245;es
Nuno Sim&#245;es

Reputation: 206

$(document).ready(function() {
    var counter = 0;
    var slides = ['<p>Track All of Your enemys Using The <span>Scout Tool!</span></p>',
                    '<p>Download powerups Using The <span>Pirate Tool!</span></p>',
                    '<p>Gather Badges To Attack others in <span>Raids!</span></p>',
                    '<p>Enjoy Orgainzing Your Profile <span>Join Now!</span></p>'];

    $('#slide-left').click(function() {
        $('#slide').fadeTo('fast', function() {
            $('#slide p').remove();
            if (counter > 0){
                counter --;
            }else{
                if (counter < (slides.length-1)){
                    counter ++;
                }
            }
            $('#slide').append(slides[counter]);
            $('#slide').fadeTo('fast', 1);
        });
    });
});

I don't know it this is correct or not, but my 5 sents :

Hope i have helped,

Upvotes: -1

loxxy
loxxy

Reputation: 13151

fadeTo accepts a third argument which is the callback function. This is called when the animation completes. So you could always do something like :

$('#slide').fadeTo('fast', 1, function() {

    // This part is executed after fade

});

Upvotes: 5

Abraham Uribe
Abraham Uribe

Reputation: 3118

you can do

$('#slide').fadeTo('fast', 0,function(){
     $('#slide p').remove();
     if (counter > 0){counter --;}
     $('#slide').append(slides[counter]).fadeTo('fast', 1);
});

Upvotes: 1

Related Questions