JSFiddle - React, Tailwind, and code Playground

by sptx457

CSS

body {
  margin: 0px;
}

img {
  width: 50px;
  height: auto;
}

.cell {
  display: inline-block;
  width: 32%;
  height: 160px;
  position: relative;
}

JavaScript

$(document).ready(function() {

  var images_array = ["1", "2", "3", "4", "5", "6", "7", "8", "9"];
  var $new_div = $("<div class='cell'>").html('<img class="icons" src="http://sarah.educatedlabs.com/images/image' + images_array + '.png" />');
  
  var generate_random_left = function(available_width) {
      var number = Math.floor(Math.random() * available_width);
      return number;
  };

  var generate_random_top = function (available_height) {
      var number = Math.floor(Math.random() * available_height);
      return number;
  };

  for (var i = 0; i < images_array.length; i++) {
    // placed inside loop to get data for all exisiting images
    var available_height = $('.cell').height() - 70;
    var available_width = $('.cell').width() - 70;
    var left = generate_random_left(available_width);
    var top = generate_random_top(available_height);
    
    // adjusts top and left if a negative number is assigned
    if (top <= 0) {
      top += 100; 
    }
    
    if (left <= 0) {
      left += 100; 
    }
    
    // loops through array and creates images
    $new_div = $("<div class='cell'>").html('<img class="icons" src="http://sarah.educatedlabs.com/images/image' + images_array[i] + '.png" />');

    $('body').append($new_div); 
    
    $(".icons").last().css({"position":"relative", "top": top, "left": left});
    
  }      
});