Search code examples
javascriptjqueryjquery-masonry

JS Random function and masonry causing issues


I'm using this code below so randomly place images, within a container, from each other. The effect works well, however, for most of the time, the function fails to load and on visiting, and all the images display awkwardly over each other on the page.

$(document).ready(function(){
  $('.each-image').each(function() {
    $(this).css({ 
       'margin-top':  Math.floor((Math.random() * 300) +1) + 'px', 
       'margin-left': Math.floor(Math.random() * 400 + 0) + 'px' });
  });
});

I am also using masonry in combination with this to avoid an overlap. The masonry is called first and organised the images, then the random function extends the distances between them all.

Masonry code:

$(document).ready(function(){
var $container = $('.content-side.individual-pages');

$container.imagesLoaded( function(){
    $container.masonry({
    itemSelector : '.each-image',
    columnWidth: 30,
    isAnimated: true
  });
});
});

Here's a link to the project: http://www.sarahstaton.com/exhibitions-installations/ and if you refresh , you'll see sometimes it works, and sometimes it doesn't.

My question, really, is if I should be using anything else, or what could I do to tighten up the random function.

Thanks, R


Solution

  • There is nothing in the code that guarantee that the images are not overlaping each other what I can see.

    Remove the Masonry code and just irritate thru the collection of "each-image" and guarantee you are using a unique margin-top on each of the images/or how do you want.

    $(document).ready(function(){
      var i = 0;
      $('.each-image').each(function() {
        i++;
        $(this).css({ 
           'margin-top':  (Math.floor((Math.random() * 300) +1) * (i*400)) + 'px', // Or change the facator to the images size
           'margin-left': Math.floor(Math.random() * 400 + 0) + 'px' });
      });
    });