Search code examples
javascriptinstagram-apimasonry

Masonry Grid : Instagram API + MacyJS - Javascript problem


I'm trying to do a masonry-like grid using Macy.js and the Instagram API.

I have an issue, the grid appears only when the windows size change.

If the page only load, the grid will not display.

Page Load: page load

After window resize: page after resize

The code:

HTML

<div id="container">
  <div id="macy-container">
  </div>
</div>

Javascipt

<script>
  /* Macy.js init */
  var macy = Macy({
    container: '#macy-container',
    trueOrder: false,
    waitForImages: false,
    margin: 24,
    columns: 4,
    breakAt: {
      1200: 4,
      940: 3,
      520: 2,
      400: 1
    }
  });

  /*Instagram API - Images */
  var token = 'MY-TOKEN',
      num_photos = 20, // maximum 20
      containerFeed = document.getElementById( 'macy-container' ), // it is our <ul id="rudr_instafeed">
      scrElement = document.createElement( 'script' );

  window.mishaProcessResult = function( dataFeed ) {
    for( x in dataFeed.data ){
      var date = new Date(dataFeed.data[x].created_time*1000);
      var dateFormat = date.toLocaleString();
      // var imgDay = date.get
      // var imgMonth
      // var imgYear
      containerFeed.innerHTML += '<div class="demo"><img src="' + dataFeed.data[x].images.standard_resolution.url + '"></div>';
    }
  }

  scrElement.setAttribute( 'src', 'https://api.instagram.com/v1/users/self/media/recent?access_token=' + token + '&count=' + num_photos + '&callback=mishaProcessResult' );
  document.body.appendChild( scrElement );
</script>

Is anyone can help me? :)

Thanks!


Solution

  • The problem is that when you're instantiating Macy.js, images are not loaded yet. You should wait until API will return all required images, and only after that instantiate Macy.js. For example, put the Macy.js instantiation code into the mishaProcessResult function, after the for loop.

    ...
    window.mishaProcessResult = function( dataFeed ) {
      for( x in dataFeed.data ){
        ...
      }
    
      /**
       * Instantiate Macy.js inside the API's callback function,
       * after required images are returned by API, and attached to the DOM.
       */
      Macy({
        // options
      });
    }
    ...
    

    Or, use Macy.js reInit method inside API's callback function:

    ...
    // Init Macy.js
    const macy = Macy({
      // options
    });
    
    window.mishaProcessResult = function( dataFeed ) {
      for( x in dataFeed.data ){
        ...
      }
    
      /**
       * Reinitialises the current macy instance
       */
      macy.reInit();
    }
    ...