Search code examples
javascriptjquery-masonrybuddypress

How to apply masonry after ajax


After clicking "Load More" in "Activity Page" of "BuddyPress", I want to apply "Masonry.js" to the activity list.

I wrote the following code for that, but $ grid.masonry after clicking "Load More" don't work.

(function($){

    if($('#activity-stream').length){

        var observer = new MutationObserver(function (MutationRecords, MutationObserver) {

            var $grid = $('.grid').masonry({ 
                itemSelector: '.grid-item',
                isFitWidth: true,
                isAnimated: true,
                columnWidth: 620,
            }); 

            $grid.masonry(); // don't work
            $grid.masonry('reloadItems'); // don't work
            $grid.masonry('layout'); // don't work

        });

        observer.observe($('#activity-stream').get(0), {
            childList: true,
        });

    }

})(jQuery);

If I add elements such as span and use settimeout as shown below, "Masonry.js" will work, but this is inappropriate.

(function($){

    if($('#activity-stream').length){

        $('body').on("click",'.load-more',function(){
            $('#activity-stream').prepend('<span></span>');
        }); 

        var observer = new MutationObserver(function (MutationRecords, MutationObserver) {

            var $grid = $('.grid').masonry({ 
                itemSelector: '.grid-item',
                isFitWidth: true,
                isAnimated: true,
                columnWidth: 620,
            }); 

            setTimeout(function(){
                $grid.masonry();
                $grid.masonry('reloadItems');
                $grid.masonry('layout');
            },5000);    

        });

        observer.observe($('#activity-stream').get(0), {
            childList: true,
        });

    }

})(jQuery);

I'm totally lost in life and don't know what to do...

It would be greatly appreciated if you could explain the details.

Thanks.

Masonry.js:https://github.com/desandro/masonry


Solution

    • When You've completed Your elements adding to the DOM (maybe with an AJAX call), then call the .layout() method on Your Masonry instance. Do not initialize Mansory more than once and do it at the Document Ready Event. See https://masonry.desandro.com/methods.html
    • If You can post the page, with the HTML maybe I can qualify my answer, it depends on the Wordpress theme used.
    • It should be possible that the definition of the Observer is been executed after the AJAX call so the Mutation is not detected