Fanick
Fanick

Reputation: 3

Javascript - Add images to a node in random positions

I'm expecting from below script the positioning of a simple image at random positions in a DIV. While the images do get displayed, they all appear side by side, while I can see on the console that the random positions are being generated. Any hint, please?

  <script type="text/javascript">
  function generateFaces(){
    var numberOfFaces = 5;
    var theLeftSide = document.getElementById("leftSide");
    while (numberOfFaces > 0) {
      var random_left = Math.floor(Math.random()*400);
      var random_top = Math.floor(Math.random()*400);
      var theImage = document.createElement("img");
      theImage.src = "face.png";
      theImage.style.top = '"'+random_top+'px"';
      console.log("top style: " + '"'+random_top+'px"');
      theImage.style.left = '"'+random_left+'px"';
      theLeftSide.appendChild(theImage);
      numberOfFaces--;
    }
  }
</script>

Thanks!

Upvotes: 0

Views: 152

Answers (1)

Deep
Deep

Reputation: 9794

Try like this.

You need to set the position relative and also set the style like this.

theImage.style = "top:"+random_top+"px; left:"+random_left+"px; position:relative";

You can check in the developer console that the style you have added for image are not actually applied on the element.

#leftSide
{
  height:400px;
  width:400px;
}
<div id="leftSide"></div>
<script type="text/javascript">
  function generateFaces(){
    var numberOfFaces = 5;
    var theLeftSide = document.getElementById("leftSide");
    while (numberOfFaces > 0) {
      var random_left = Math.floor(Math.random()*400);
      var random_top = Math.floor(Math.random()*400);
      var theImage = document.createElement("img");
      
      theImage.src = "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcR9tLvsasK-kB72yV_zC8hn0qZhHbshQdXLELCXaF1JkWIOuYfUUsuMsw";
      theImage.style = "top:"+random_top+"px; left:"+random_left+"px; position:relative";
      theLeftSide.appendChild(theImage);
    
     
      numberOfFaces--;
    }
  }
  generateFaces();
</script>

Upvotes: 1

Related Questions