11

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!

Smandoli
  • 6,919
  • 3
  • 49
  • 83
Dave
  • 111
  • 1
  • 4

3 Answers3

9

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
    });
  });
  • I can't seem to get this to work - does this replace the masonry script in the html - is #masonry the container and .children the class on the div? – mark Jun 08 '11 at 22:59
  • I don't think this can work because of the nature of masonry. – Micromega Nov 30 '11 at 03:37
  • 1
    The snippet above works great. You need to change all instances of #masonry to match your masonry container. Also, you can use $('#masonry').masonry('reload'); after the shuffle if the grid is already live. – askon Jan 18 '12 at 05:06
2

I think a more appropriate plugin for your would be Isotope, it's built the same way as Masonry (and by the same guy!) but has sorting and filtering features built-in

Charlotte Dann
  • 298
  • 2
  • 10
1
(function($) {

$.fn.randomize = function(childElem) {
  return this.each(function() {
      var $this = $(this);
      var elems = $this.children(childElem);

      elems.sort(function() { return (Math.round(Math.random())-0.5); });  

      $this.remove(childElem);  

      for(var i=0; i < elems.length; i++)
        $this.append(elems[i]);      

  });    
}
})(jQuery);


$(window).load(function(){
  $(masonry-container).randomize(masonry-brick).masonry('reload');
});
Justin
  • 11
  • 1