Why image inline instead of random inside of div?

- 1 answer

Ad

Im trying to create left side of a matching game and I failed to randomly place the images. They always appear in a horizontal line instead of randomly in the div. Please advice, really appreciated!

edited: This isnt a duplicate question. As required, I cant link any outside CSS or JS file in making of this game.

edited: never mind, maybe it is a relative question to a previous one. Search didnt come up with that result thus the asking.

<!DOCTYPE html>
<html>

<head>
</head>

<header>
    <h1>Matching Gmae</h1>
    <p>Click on the extra smilling face on the left.</p>
</header>

<body onload="generateFaces()">
    <!--division styling -->
    <!--left-->
    <div id="leftSide" style="position:absolute; width:500px; height:500px"></div>
    <!--right-->
    <div id="rightSide" style="position:absolute; width:500px; height:500px; left:500px; border-left: 1px solid black;"></div>


    <!-- starting Javascript-->
    <script>
        var numberOfFaces = 5;
        var i = 0;
        var theLeftSide = document.getElementById("leftSide");

        function generateFaces() {
            while (i < numberOfFaces) {
                var img = document.createElement("img");
                img.src = "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
                img.style.top = Math.floor(Math.random() * 400) + "px";
                img.style.left = Math.floor(Math.random() * 400) + "px";
                theLeftSide.appendChild(img);
                i += 1;
            }
        }
    </script>>
</body>

</html>

enter image description here

Ad

Answer

Ad

As @Xufox wrote in the comment, a non-static position should be set for the top and left to have any effect.

The "duplicate" question does not explain how to do that in JavaScript, though.

In your script, that means you should add:

img.style.position = 'absolute';
Ad
source: stackoverflow.com
Ad