Diane Corrigan
Diane Corrigan

Reputation: 11

Trouble getting images to display at random positions using javaScript

I am trying to generate 5 images on the left-hand side of the page in random positions. The images are displayed in a row across the top and not in the random positions that I require. I do have img{position:absolute} within my CSS. I am sorry if this has been covered previously, I have searched endlessly for an answer and tried many different examples, but I am still stuck, can someone point me in the right direction, please.

<script>
    var numberOfFaces = 5;
    var theLeftSide = document.getElementById("leftSide");

    function getRandom(x, y) {
        return Math.floor(Math.random() * (y - x)) + x + 'px';
    };

    function generateFaces() {
      for (var i=0; i<numberOfFaces; i++) {
        var faces = document.createElement("img");
        faces.src = "smile.png";
        faces.style.top = getRandom(0, 400);
        faces.style.left = getRandom(0, 400);
        leftSide.appendChild(faces);
      };
    };

    </script>

Upvotes: 0

Views: 60

Answers (1)

Man Programmer
Man Programmer

Reputation: 5356

http://jsfiddle.net/pynaam1f/

OR

http://jsfiddle.net/pynaam1f/1/

img{
    position:absolute;
}

Upvotes: 1

Related Questions