Kyslik
Kyslik

Reputation: 8385

jQuery animation callback called too fast

So I am trying to animate .load('content.html') function by doing this.

function loadContent(c) {
    $('#main-container').stop().animate({
        opacity: 0,
    }, 300, function() {
        $('#main-container').load('./content/' +  c + '.html');
        $(this).stop().animate({
            opacity: 1,
        }, 600);
    });
}

It is pretty straight forward, I want to animate opacity to 0, load new content and animate opacity back to 1. The problem is that content loads immediately after function is called so content changes before 'opacity 0' happens. I tried also this piece of code

function loadContent(c) {
    $('#main-container').stop().animate({
        opacity: 0,
    }, 300, function() {
        setTimeout(function() {
            $('#main-container').load('./content/' +  c + '.html');
        }, 600);

        $(this).stop().animate({
            opacity: 1,
        }, 600);
    });
}

But it is same result. Any hints?

I think it has something to do with .animation() event being asynchronous.


Both codes above, and both answers work just fine I had typo in my code (as whole) so I was calling .load() function before loadContent(c) itself, result was that content loaded immediately, animation started -> content loaded second time -> animation ended.

Upvotes: 2

Views: 558

Answers (2)

Banana
Banana

Reputation: 7484

how about:

function loadContentCOMMAS(c) {
    $('#main-container').stop().animate({
        opacity: 0
    }, 300);
    $('#main-container').promise().done(function () {
        $('#main-container').load(c,function () {;
            $(this).stop().animate({
                opacity: 1
            }, 600);
        });
    });
}

EDIT:

here is a FIDDLE

Upvotes: 0

James Duffy
James Duffy

Reputation: 1387

You need to pass your last animation as a callback function to load():

function loadContent(c) {
    $('#main-container').stop().animate({
        opacity: 0
    }, 300, function() {
        $('#main-container').load('./content/' +  c + '.html', function() {
            $(this).stop().animate({
                opacity: 1
            }, 600);
        });
    });
}

Here's a Fiddle: http://jsfiddle.net/Lp728/

Upvotes: 1

Related Questions