Display 'loading' until all images have loaded and jquery Masonry triggers

Jesse picture Jesse · Sep 18, 2011 · Viewed 20.9k times · Source

I am using the jquery Masonry plugin and looking to hide all content until after the plugin triggers. Masonry by default loads all images before it triggers. I want to display a 'loading' div until the plugin has triggered. I have implemented a page that checks the resolution is above 1024px, then displays a 'loading' div as the page loads but right now page content appears before the plugin triggers.

<script>

$(document).ready(function() {
    $('#content').show();
    $('#loading').hide();
});

$(function(){

var $container = $('#container');
var width = $(window).width(); 
var height = $(window).height(); 

if ((width > 1024  )) {

$container.imagesLoaded( function(){
  $container.masonry({
    itemSelector : '.box',
    columnWidth: 120,
      });
    });

    }
    else {
    //load the css styles for screen res below 1024
    }

});

</script>

See working example here.

As you can see there is a delay between the content appearing and the plugin triggering. Hoping someone can help me delay the content appearing unit after trigger?

Cheers - Jesse

Answer

frozenkoi picture frozenkoi · Nov 8, 2011

Masonry adds the "masonry" css class to the container after it finishes setting up the bricks. Just add css rules to hide the DIV.

For example, if you have

<div id="container">
    <div id="loading">Loading...</div>
    [items to use in the masonry layout]
    <div class="box">1</div>
    <div class="box">2</div>
</div>

then in the CSS use

#container.masonry #loading {display: none}

and have rules that make the box'es invisible until the plugin finishes

#container .box {position: absolute; top: -1000px; left: -1000px}

masonry will give it inline styles to the box'es for position: absolute, top and left anyway. You will, of course, have to tailor this to your own site.

That should make the DIV with id "loading" to disappear after masonry is done setting up the box'es.