Randomize bricks in Masonry

Dave picture Dave · Feb 15, 2011 · Viewed 9k times · Source

is it possible to randomize the bricks in the JQuery plugin Masonry so that every time the page loads a different arrangement is viewed? There is no option for random as far as I can tell.

Thanks!

Answer

user1151 picture user1151 · Apr 8, 2011

I found an answer over on the jQuery forums and I tweaked it a bit for my needs. In short - you pull the HTML bits inside your masonry() holder and you randomize the collection, then you put it back:

  $(document).ready(function(){
    var ar = $('#masonry').children();
    ar.sort(function(a,b){
      // Get a random number between 0 and 10
      var temp = parseInt( Math.random()*10 );
      // Get 1 or 0, whether temp is odd or even
      var isOddOrEven = temp%2;
      // Get +1 or -1, whether temp greater or smaller than 5
      var isPosOrNeg = temp>5 ? 1 : -1;
      // Return -1, 0, or +1
      return( isOddOrEven*isPosOrNeg );
    });
    $('#masonry').html(ar);
    $('#masonry').masonry({ 
      columnWidth:220,
      animate: true
    });
  });