Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Masonry is not working until resize window

I have seen this posted a couple of times on here but neither had a solution which has worked.

I am using jquery masonry to lay out lots of divs with an image and caption inside.

I have set "height:auto;" for the css of each item in the masonry. I expected that once the window has loaded then the masonry would take effect and lay out the content as it should. Unfortunately, it loads with 4 columns but the images are all overlapped in height. If i set the height in px for the css then it works, but the website is responsive and I need the height at auto preferably, as I don't want to change the css height through each media query...

Appreciate any help :)

Thanks

The JS code is:

    $(window).load(function()
{
    var columns    = 4,
        setColumns = function() { columns = $( window ).width() > 700 ? 4 : $( window ).width() > 480 ? 2 : 1 };

    setColumns();
    $( window ).resize( setColumns );

    $( '#container' ).masonry(
    {
        itemSelector: '.item',
        gutterWidth: 66,
        isFitWidth: true,
        isAnimated: true,
        columnWidth:  function( containerWidth ) { return containerWidth / columns; }
    });
});
like image 426
JByrne Avatar asked Dec 06 '25 19:12

JByrne


2 Answers

You should definitely use imagesLoaded: http://imagesloaded.desandro.com/

Implemented as so:

  //le masonry
  var freeMasonry = $('.masonry');

  freeMasonry.imagesLoaded()
    .done(function(){
      freeMasonry.masonry({
        itemSelector: 'img'
      });
    });
like image 141
hellojebus Avatar answered Dec 08 '25 11:12

hellojebus


I had to apply a height:XXpx'to each item in the masonry. And then alter that height for the @mediaqueries. Not quite what I was hoping but it worked! Thank you for your idea though.I'm may have just implemented it incorrectly.

Without the height in the CSS for the items in the masonry, it simply overlapped the images etc. I am told through research the .imagesloaded function can be used to achieve this by setting the div height after the images inside the div have loaded. But for me this was the simplest solution.

like image 42
JByrne Avatar answered Dec 08 '25 09:12

JByrne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!