Ankur
Ankur

Reputation: 51110

Prepend items to jQuery Masonry

I have been able to append items to jQuery masonry quite happily in order to create an "infinite scroll" affect.

I naively thought similar strategies would work for adding content before the Masonified content.

I setup masonry like this:

$(document).ready(function(){

   var $container = $('#pics');
        $container.imagesLoaded( 
        function(){
            $container.masonry({ 
            itemSelector : '.item',
            isFitWidth: true,
            isAnimated: true });
        });
});

The original images appear within this loop (using Playframework 1.2.4 with Java)

<div id="pics" class="pics">
            #{list items:pics, as:'pic'}
                <div class="item">
                    <a href="https://s3.amazonaws.com/bucket/${pic.url}"/>
                    <img src="https://s3.amazonaws.com/bucket/${pic.url}" class="pic" style="height:${pic.height}">
                    </a>
                </div>
            #{/list}
</div>

And this is where I am adding the new pictures into the Masonified "newpics" div:

  $.each(data.files, function (index, file) {

var filename_leaf = milliTime+"-"+file.name;
var filename_stem = "https://s3.amazonaws.com/bucket/";
var filename = filename_stem+filename_leaf;

var newpic = "<div class='item'>"+
   "<a href='"+filename+"'>"+
   "<img src='"+filename+"'"+
   " class='pic' style='height:"+file.height+"'>"+
   "</a></div>";

$('#pics').prepend(newpic).masonry('reload');

 });

What happens is that the pictures are prepended, however they fall behind the existing pictures.

If there was someway of refreshing/reloading the #pics div without refreshing the whole page that would pretty much solve the problem. I'm going to keep looking, but I suspect that someone else may know a better way.

Upvotes: 1

Views: 2083

Answers (2)

Panama Jack
Panama Jack

Reputation: 24468

Just incase someone finds this. reload doesn't work on the current version if you prepend a new element. You have to use prepended. Seems like every site references reload. Must be for previous versions.

msnry.prepended( elements )
// or with jQuery
$container.masonry( 'prepended', elements )

http://masonry.desandro.com/methods.html

Upvotes: 0

Simon Boudrias
Simon Boudrias

Reputation: 44629

Your problem isn't with Masonry. Your bug is that once the new photo is uploaded, the height value is undefined. This means that your picture markup look like this:

<img style="height:undefined" class="pic" src="/photo.jpg">

This causes problems because until getting the image, most browsers will render the picture as being height: 0. And this is what making the reload of the masonry mosaic "buggy" (it relayout the mosaic considering the first new image as being 0px in height).

So, you should make sure you got a valid value for the height of the image. Or wait until the image is fully loaded to trigger the reload method.

Upvotes: 2

Related Questions