Max
Max

Reputation: 27

Is there a way to execute another function by ".empty" function in jQuery?

Look at my code here

$('#UpdatesButton').click(function() {
    $('.content').fadeOut(200, function() {
        $(".content").empty(function() {
            $('.content').load('Pages/Updates.php', function() {
                $('.content').fadeIn(200);
            });
        });
    });
});

Because .empty() don't accept any arguments, my code stops on the line where .empty function is (https://api.jquery.com/empty/), what I am wishing to do is to somehow continue execution of .load and .fadeIn functions right after .empty completed it's own execution, but it seems impossible, is there alternatives to empty the .content (which is a DIV container)?

Upvotes: 0

Views: 53

Answers (2)

SeinopSys
SeinopSys

Reputation: 8937

It's a micro optimization, but starting to load the data before fade out can cut down on the overall loading time. This code does essentially the same, but starts the request for the data in parallel with the fadeOut, and it handles race conditions.

  • When the data is loaded before the fade out, the code does nothing, as the element is still animated, and the fadeOut callback will see the updated data variable after the animation, triggering the content update
  • If the data loads after the fade out, the animation callback will do nothing because of the empty data variable, but the element won't be animated any more, and the AJAX callback will trigger the update instead.
$('#UpdatesButton').click(function() {
    var $content = $('.content'),
        data;
    $.ajax({
        url: 'Pages/Updates.php',
        dataType: 'text',
        success: function(result){
            data = result;
            if (!$content.is(':animated'))
                $content.html(data).fadeIn(200);
        }
    });
    $content.fadeOut(200, function(){
        if (typeof data !== 'undefined')
            $content.html(data).fadeIn(200);
    });
});

Upvotes: 0

Satpal
Satpal

Reputation: 133433

You don't need callback for empty, Simple chaining will do like

$('#UpdatesButton').click(function() {
    var elem = $('.content');
    elem.fadeOut(200, function() {
        elem.empty().load('Pages/Updates.php', function() {
            elem.fadeIn(200);
        });
    });
});

However as per my understanding You don't need empty() at all, .load() will update the content

$('#UpdatesButton').click(function() {
    var elem = $('.content');
    elem.fadeOut(200, function() {
        elem.load('Pages/Updates.php', function() {
            elem.fadeIn(200);
        });
    });
});

Upvotes: 2

Related Questions