DrSocket
DrSocket

Reputation: 135

Generate Randomly placed images with javascript

I'm trying to place 5 images randomly on a div called "leftSide" with width & height '500px' the img has width & height '100px' so I'm trying to generate the 5 images in the a range where it fits in the div.

I think this is all the relevant code:

numberOfFaces = 5
var theLeftSide = document.getElementById("leftSide");
while (numberOfFaces > 0) {
    var img = document.createElement('img');
    img.src = "smile.png";
    valueTop = Math.floor(Math.random() * 400);
    valueL = Math.floor(Math.random() * 400);
    img.style.top = valueTop + 'px';
    img.style.left = valueL + 'px';
    theLeftSide.appendChild(img);
    numberOfFaces -= 1;

I'd appreciate any idea's what I could be doing wrong and how to fix it. Thanks! This should be solved without any libraries like jQuery

Upvotes: 3

Views: 228

Answers (2)

Phoenix
Phoenix

Reputation: 487

This is how i have done.

$(document).ready(function() {
  var imgCre, postop, posleft,posTopArray=[],posLeftArray=[];
  for (var i = 0; i < 5; i++) {
    postop = Math.floor((Math.random() * 400) + 1);
    posleft = Math.floor((Math.random() * 400) + 1);
    posTopArray[i] = postop;
    posLeftArray[i]= posleft;
     for(var j= 0;j<i;j++){
       
       if(posTopArray[j]==postop)
         postop = Math.floor((Math.random() * 400) + 1);//new random position if any of old position match with new
         
     }
    imgCre = "<img src='http://lorempixel.com/100/100/' style='width:100px; height:100px; position:absolute; top:" + postop + "px; left:" + posleft + "px'>";
    $("#imaggeContainer").append(imgCre);
  }
});
body {
  margin: 0px;
  padding: 0px;
  background-color: #555;
}
#imaggeContainer {
  width: 500px;
  height: 500px;
  border: 5px solid #f9d899;
  background-color: #999;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="imaggeContainer">
  <div>

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386550

You need to add

img.style.position = 'absolute';

for every inserted image.

And for the leftSide this:

<div id="leftSide" style="position: relative;">...

var numberOfFaces = 5;
while (numberOfFaces--) {
    var img = document.createElement('img');
    img.src = "http://lorempixel.com/50/50/cats/" + numberOfFaces;
    var valueTop = Math.random() * 400 | 0;
    var valueL = Math.random() * 400 | 0;
    img.style.top = valueTop + 'px';
    img.style.left = valueL + 'px';
    img.style.backgroundColor = '#0000ff';
    img.title = 'left: ' + valueL + ' top: ' + valueTop;
    img.style.position = 'absolute'; // <--------------------------------------- add this!
    document.getElementById('leftSide').appendChild(img);
}
<div id="leftSide" style="position: relative; padding: 0; border: 0; width: 500px; height: 500px; background-color: #ffff00;">

Upvotes: 2

Related Questions