Why image inline instead of random inside of div?

- 1 answer


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>


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

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

    <!-- starting Javascript-->
        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";
                i += 1;


enter image description here




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';
source: stackoverflow.com