Search code examples
jqueryappendto

Empty container before .appendTo() is fired using jquery


I have a container #boxes that I need to empty and add content to using .imagesLoaded() and then applying masonry. The content by default contains masonry items which I'm removing and then adding new ones contained within the response. The problem with my code is that it's emptying the content after the append I believe. Any ideas?

$(document).ready(function($){
    $('div.profile-archive').click(function(){
        $("#boxes").empty();
        $this = $(this);
        var postType = $this.attr("rel");
        data = {
          action: 'fetch_profile_archive',
              postType : postType
        };
        $.post(ajaxurl, data, function (response) {
            var $response = $(response);
            $response.imagesLoaded(function() {
              $("#boxes").masonry('reload');
            }).appendTo("#boxes");
        });
    });

});

Solution

  • I think your problem lies in the imagesloaded function. You currently append the result from imagesloaded to boxes, my guess is you have add the response to boxes first and then run imagesLoaded on boxes.

    $("#boxes")
      .append($response)
      .hide() // If you don't want to show the content until loaded
      .imagesLoaded(function() {
        $("#boxes")
          .show() // If you want to show the content after it's loaded
          .masonry('reload');
      });