abaracedo
abaracedo

Reputation: 1454

Masonry not initialising correctly after ajax call

I'm using this plugin to set a grid gallery. This gallery shows X number of images. These images are loaded into the HTML after an ajax call:

$.ajax({
    type:"POST",
    dataType:"html",
    contentType:"application/x-www-form-urlencoded",
    url:url,
    data:data,
    success:function(response) {

       $("#masonry-container").html('<div id="content">'+response+'</div>');
       initialiceMasonry();

    }
    ,timeout:10000
});

As you can see, after appending the server response it calls initialiceMasonry();

var container = $("#content");

container.masonry({
    columnWidth:190,
    itemSelector:".item",
    gutter:8,

});

After that initialisation the images are shown overlapped, looking for another questions about this plugin I found the option to use imagesLoaded but it returns me this error:

Uncaught TypeError: undefined is not a function 

And selects the line where i call imagesLoaded

From server i get this HTML:

    <div class="item" data-id="160">

        <img src="image_1.jpeg" />

        <div class="options">
            <h4>Section 1</h4>
            <a href="section_1.php">Section 1</a>
        </div>

    </div>

How can I initialise Masonry correctly to fix my overlapping problem?

Upvotes: 0

Views: 3597

Answers (1)

v2solutions.com
v2solutions.com

Reputation: 1439

Well i think you can use reload callback of this plugin so in your success function of ajax you can call your initialiceMasonry() function which will look like this

function initialiceMasonry(){
    var $container = $('#masonry-container');        
        $container.imagesLoaded(function() {               
            $container.masonry('reload');
            $container.masonry({
                isInitLayout : true,
                itemSelector: '.mason_jar_item'
            });
        });

Upvotes: 6

Related Questions