4

I want to position append an image inside a div. The image should be displayed 5 times within a height of 500 and width of 500. They should be positioned randomly be in different places but they should not cross the height and width of the div.But my code produces a result where the images are always positioned in an inclined line right to left and always creating faces which are together.

Here's my code:

        var theLeftSide = document.getElementById("leftSide");  
        var top_position = Math.random() *   500 - 100;
        var left_position = Math.random() *  500 - 100;
        numberOfFaces = 5;
        function generateFaces() {          
            for (var i = 0; i < 6; i++) {
                createElement(i);
                numberOfFaces += numberOfFaces;
            }
        } 
        function createElement() {
            var image = document.createElement('img');
            image.src = "smile.png";
            image.style.position = 'absolute';
            image.style.top = top_position + "px";
            image.style.left = left_position + "px";
            theLeftSide.appendChild(image);
            top_position += 20;
            left_position += 20;
        }
Joy
  • 109
  • 2
  • 10

1 Answers1

2

The images are being placed in a diagonal line becauset you are incrementing top_position and left_position by 20 every call. Basically you pick a random start, e.g. 10, 15, for smiley one. Then smiley two gets placed at 30, 45, smiley three at 50, 65, etc. To fix this you need to regenerate both positions for every image.

The following code will do what you want. I added getRandomInt from MDN (here) to make it a little easier to get a number you want.

var theLeftSide = document.getElementById("leftSide");  
var top_position;
var left_position;
numberOfFaces = 5;
function generateFaces() {        
    for (var i = 0; i < 6; i++) {
        top_position = getRandomInt(0, 500);
        left_position = getRandomInt(0, 500);
        createElement(i);
        numberOfFaces += numberOfFaces;
    }
} 
function createElement() {
    var image = document.createElement('img');
    image.src = "smile.png";
    image.style.position = 'absolute';
    image.style.top = top_position + "px";
    image.style.left = left_position + "px";
    theLeftSide.appendChild(image);
}
function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
}

Keep in mind this does not respect the bounds of the div. For that you would have to set the div's position to relative, set a width and height, and update this code to get the divs dimentions (for example, using the answer here). The images should be positioned based on their top left corner so you would also need to subtract the width and height of the image from the width and height used to generate the random position numbers to prevent images from overflowing on the bottom or right.

Community
  • 1
  • 1
Marie
  • 2,114
  • 1
  • 17
  • 31